<?php

namespace app\company\controller;

use app\common\lib\SendIntegralNew;
use think\Db;
use think\Exception;
use think\Paginator;
use think\Request;
use League\Csv\Reader;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use app\company\logic\Message;
use app\company\logic\Export;
class Integral extends Base
{

    public function _initialize()
    {
        parent::_initialize();
    }

    //事件库
    public function activity()
    {
        $name = I('name', '');
        $type = I('type', 1);
        $type_event_id = I('type_event_id',0);
        if (!empty($name)) {
            $where['a.name'] = ['like', "%{$name}%"];
        }

        if (!empty($type)) {
            $where['a.type'] = $type;
        }
        if (!empty($type_event_id)) {
            $where['a.cate_id'] = $type_event_id;
        }
        $com_id = $this->com_id;

        $where['a.com_id'] = $com_id;
        $export = I('export', 0);
        $where['a.is_del'] = 0;//未删除
        if ($export == 1) {
            $list_a = M('com_event a')
                ->join('com_event_cate b', 'a.cate_id = b.id', 'left')
                ->join('com_event_cate c', 'b.pid = c.id', 'left')
                ->where($where)
                ->field('a.*,b.name cate_name,c.name p_cate_name')
                ->select();
            $this->activity_export($list_a);
        }
        $list = M('com_event a')
            ->join('com_event_cate b', 'a.cate_id = b.id', 'left')
            ->join('com_event_cate c', 'b.pid = c.id', 'left')
            ->where($where)
            ->field('a.*,b.name cate_name,c.name p_cate_name')
            ->order('a.create_time desc')
            ->paginate('', false, page_param());
        $where_1['a.com_id'] = ['in', [$this->com_id, 0]];
        $list_user = M('com_event_cate a')
            ->join('com_event_cate b', 'b.id = a.pid', 'left')
            ->field('a.*,b.name p_name')
            ->where($where_1)->select();
        $this->assign('list_user', $list_user);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //事件编辑
    public function activity_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->activity_store($request);
        }
        $id = I('id', 0);
        $list = M('com_event')->where('id', $id)->find();

        $cateid = $list['cate_id'];
        $tmpCateIds = [$cateid];
        while (true) {
            $cateid = db('com_event_cate')->where('id',$cateid)->find();
            if(!$cateid['pid']){
                $tmpCateIds = array_merge($tmpCateIds, [$cateid['id']]);
                break;
            }else{
                $tmpCateIds = array_merge($tmpCateIds, [$cateid['pid']]);
            }
            $cateid = $cateid['pid'];
        }
        $cateNames = db('com_event_cate')->where('id','in', $tmpCateIds)->column('name');
        $list['c_name'] = implode('/', $cateNames);

        if($list['is_check']??''){
            $list['fuser'] = db('users a')
                ->join('com_department b', 'a.department_id = b.id', 'left')
                ->where('a.id', 'in', $list['first_check_user_id'])
                ->column('a.id,a.name,a.job_number,b.name as department_name');

            $list['luser'] = db('users a')
                ->join('com_department b', 'a.department_id = b.id', 'left')
                ->where('a.id', 'in', $list['last_check_user_id'])
                ->column('a.id,a.name,a.job_number,b.name as department_name');
        }

        $this->assign('info', $list);

        return $this->fetch();
    }

    //事件库编辑或添加提交
    public function activity_store()
    {
        $params = input();

        $result = $this->validate($params,'Activity');
        if(true !== $result){
            return $this->ajaxReturn(1, $result);
        }

        $data = [
            'com_id'=>$this->com_id,
            'name'=>$params['name'],
            'cate_id'=>$params['cate_id'],
            'integral_a_start'=>$params['integral_a_start'],
            'integral_a_end'=>$params['integral_a_end'],
            'integral_b_start'=>$params['integral_b_start'],
            'integral_b_end'=>$params['integral_b_end'],
            'is_lottery_ticket'=>$params['is_lottery_ticket'],
            'is_piece'=>$params['is_piece'],
            'is_check'=>$params['is_check'],
            'desc'=>$params['desc'],
//            'is_lock_first'=>$params['is_lock_first']??'',
//            'is_lock_last'=>$params['is_lock_last']??'',
        ];

        if($params['is_check']) {
            if(empty($params['first_checked'])){
                return $this->ajaxReturn(1,'请选择初审人');
            }
            if(empty($params['last_checked'])){
                return $this->ajaxReturn(1,'请选择终审人');
            }
            $data['first_check_user_id'] = implode(',', $params['first_checked']);
            $data['last_check_user_id'] = implode(',', $params['last_checked']);
        }
        $where_event['com_id'] = $this->com_id;
        $where_event['name'] = $params['name'];
        $where_event['is_del'] = 0;
        if ($params['id']) {
            $where_event['id'] = ['neq',$params['id']];
            //判断是否重名
            $res = M('com_event')->where($where_event)->find();
            if(!empty($res)){
                return $this->ajaxReturn(1,'该名称已存在');
            }
            db('com_event')->where('id', $params['id'])->update($data);
        } else {
            //判断是否重名
            $res = M('com_event')->where($where_event)->find();
            if(!empty($res)){
                return $this->ajaxReturn(1,'该名称已存在');
            }
            $data['create_time'] = time();
            db('com_event')->insert($data);
        }
        return $this->ajaxReturn(0, '成功', url(CONTROLLER_NAME . '/activity'));
    }

    //删除
    public function activity_del(){
        $params = input();
        $ids = explode(',', $params['id']);
        $where = ['id'=>['in', $ids], 'com_id'=>$this->com_id];
//        $relation_where = ['event_id'=>['in', $ids], 'com_id'=>$this->com_id];
//        $relation_info = db('com_integral_prize_buckle_relation_event')->where($relation_where)->distinct(true)->column('event_id');
//        if($relation_info){
//            return $this->ajaxReturn(1, '删除失败 已有事件被使用');
//        }
        db('com_event')->where($where)->update(['is_del'=>1]);
        return $this->ajaxReturn(0, '成功');
    }

    //移动事件 author:zj
    public function event_change()
    {
        //正式移动到临时事件。临时事件无计件和锁定审核人功能
        $params = input();
        $cate_id = $params['cate_id']??0;
        $event_ids = implode(',', $params['id']);
        $type = $params['type']??1;   //1：正式事件，2：临时事件
        $moveType = $params['move_type']??0;  //0：移动到正式库，1移动到临时库

//        $event_cate_exists = db('com_event_cate')->where('id', $cate_id)->find();
//        $event_exists = db('com_event')->where('id', $event_id)->find();
//        if(!$event_cate_exists || !$event_exists){
//            return json(['err'=>1]);
//        }

        $update = [];

        if($moveType == 1 && $type == 1) {      //正式事件，移动到临时事件
            $update = [
                'is_piece'=>0,
                'is_check'=>0,
                'is_lock_first'=>0,
                'is_lock_last'=>0,
                'type'=>2,
            ];
        }
        if($moveType == 0 && $type == 2) {
            $update['type'] = 1;
        }

        $update['cate_id'] = $cate_id;

        db('com_event')->where('id', 'in', $event_ids)->update($update);

        return $this->ajaxReturn();
    }

    //事件库分类
    public function activity_cate()
    {
        $where['a.com_id'] = ['in', [$this->com_id, 0]];
        $where['a.is_del'] = 0;
        $where['b.is_del'] = 0;
        $list = M('com_event_cate a')
            ->join('com_event_cate b', 'b.id=a.pid', 'left')
            ->field('a.*,b.name name_p')
            ->where($where)
            ->paginate('', false, page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }

    //分类编辑
    public function cate_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->cate_store($request);
        }
        $id = I('id', 0);
        $list = M('com_event_cate a')
        ->join('com_event_cate b','a.pid = b.id','left')
        ->field('a.*,b.name as pid_name')
        ->where('a.id', $id)->find();
        // $list_user = M('com_event_cate')->where('pid', 0)->select();
        // $list_user_a = M('com_event_cate a')
        //     ->join('com_event_cate b','b.pid = a.id','left')
        //     ->where('a.pid = 0 and b.com_id = '.$this->com_id)
        //     ->field('b.*')
        //     ->select();
        // $list_user = array_merge($list_user,$list_user_a);
        // $this->assign('list_user', $list_user);
        $this->assign('info', $list);

        return $this->fetch();
    }

    //事件分类编辑或添加提交
    public function cate_store()
    {
        $params = input();
//        var_dump($params);die;
        $result = $this->validate(
            $params,
            ['name' => 'require|max:50',
            ],
            ['name.require' => '标题必填',
                'name.max' => '标题最多50个字符',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if(empty($params['pid'])){
            return $this->ajaxReturn(1, '上级分类不能为空');
        }
        if (!empty($params['id'])) {
            if($params['id'] == $params['pid']){
                return $this->ajaxReturn(1, '不能选择自己为上级');
            }
            //如果有下级分类不能修改
            $c_id = M('com_event_cate')->where('pid',$params['id'])->find();
            if(!empty($c_id)){
//                return $this->ajaxReturn(1,'有下级分类不能修改');
            }
            db('com_event_cate')->where('id', $params['id'])->update($params);
        } else {
            $params['com_id'] = $this->com_id;
            $data = [
                'com_id'=>$this->com_id,
                'pid'=>$params['pid'],
                'name'=>$params['name'],
            ];
            //查询否有同名
            $where = [
                'name'=>$params['name'],
                'com_id'=>$this->com_id,
                'is_del'=>0
            ];
            $res = db('com_event_cate')->where($where)->find();
            if($res){
                return $this->ajaxReturn(1,'该分类名称已存在');
            }
            db('com_event_cate')->insert($data);
        }
        return $this->ajaxReturn(0, '成功', url(CONTROLLER_NAME . '/activity_cate'));

    }

    //删除
    public function cate_del()
    {
        $params = input();
        $ids = explode(',', $params['id']);
        $event_cate_exists = db('com_event_cate')->where(['pid'=>['in', $ids],'is_del'=>0])->find();
        if($event_cate_exists){
            return $this->ajaxReturn(1, '删除失败 请先删除下级分类');
        }
        $com_event_exists = db('com_event')->where(['cate_id'=>['in', $ids],'is_del'=>0])->find();
        if($com_event_exists){
            return $this->ajaxReturn(1, '删除失败 请先删除分类下的事件');
        }
        db('com_event_cate')->where('id', 'in', $ids)->update(['is_del'=>1]);
        return $this->ajaxReturn(0, '成功');
    }

    //移动
    public function activity_move()
    {
        $id = I('id', 0);
        $type = I('type', 0);
        $cate_id = I('cate_id', 0);
        if (empty($id)) {
            return $this->ajaxReturn(1, 'id不能为空');
        }
        if (empty($type)) {
            return $this->ajaxReturn(1, '事件类型不能为空');
        }
        if (empty($cate_id)) {
            return $this->ajaxReturn(1, '分类不能为空');
        }
        $data = [
            'type' => $type,
            'cate_id' => $cate_id,
        ];
        M('com_event')->where('id', $id)->update($data);
        return $this->ajaxReturn(0, '移动成功');
    }

    //事件库导出Excel
    public function activity_export_1($data)
    {
        set_time_limit(0);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">分类</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">A分</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">B分</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">创建时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
        $strTable .= '</tr>';
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                if (empty($val['p_cate_name'])) {
                    $val['cate_name'] = $val['p_cate_name'] . '/' . $val['cate_name'];
                }
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['cate_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['integral_a_start'] . '-' . $val['integral_a_end'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['integral_b_start'] . '-' . $val['integral_b_end'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i', $val['create_time']) . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['desc'] . '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        unset($list);
        $name = '积分管理-事件库管理';
        downloadExcel($strTable, $name);
        exit();

    }
    //事件库导出@stone
    public function activity_export($data){
        set_time_limit(0);
        import('PHPExcel/PHPExcel', EXTEND_PATH);
        $obj = new \PHPExcel();
        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj->getActiveSheet(0)->setTitle(date('Y-m-d',time()).'事件列表');   //设置sheet名称
        $_row = 1;   //设置纵向单元格标识
        $title=[
            '分类',
            '名称',
            'A分',
            'B分',
            '创建时间',
            '备注',
        ];
        if($title){
            $i = 0;
            foreach($title AS $v){   //设置列标题
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);

                $i++;
            }
            $_row++;
        }
        //设置样式
        $obj->getActiveSheet()->getStyle( 'A1:F1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        //设置背景样式
        $obj->getActiveSheet()->getStyle( 'A1:F1')->getFill()->getStartColor()->setARGB('FF808000');
        //设置单元格格式:文本
        $obj->getActiveSheet()->getStyle('C')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $obj->getActiveSheet()->getStyle('D')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $obj->getActiveSheet()->getStyle('F')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        //设置宽度
        $obj->getActiveSheet()->getColumnDimension( 'C')->setAutoSize(true);
        $obj->getActiveSheet()->getColumnDimension( 'D')->setAutoSize(true);
        $obj->getActiveSheet()->getColumnDimension( 'E')->setAutoSize(true);
        $obj->getActiveSheet()->getColumnDimension( 'F')->setAutoSize(true);
//        $obj->getActiveSheet()->getColumnDimension( 'H')->setAutoSize(true);
        $obj->getActiveSheet()->getColumnDimension( 'A')->setWidth(25);
        $obj->getActiveSheet()->getColumnDimension( 'B')->setWidth(25);
        //填写数据
//        var_dump($data);die;
        if($data){
            $i = 0;
            foreach($data AS $_v){
                if (!empty($_v['p_cate_name'])) {
                    $_v['cate_name'] = $_v['p_cate_name'] . '/' . $_v['cate_name'];
                }
                $obj->getActiveSheet(0)->setCellValue($cellName[0] . ($i+$_row), $_v['cate_name']);
                $obj->getActiveSheet(0)->setCellValue($cellName[1] . ($i+$_row), $_v['name']);
                $obj->getActiveSheet(0)->setCellValue($cellName[2] . ($i+$_row), $_v['integral_a_start'] . '-' . $_v['integral_a_end']);
                $obj->getActiveSheet(0)->setCellValue($cellName[3] . ($i+$_row), $_v['integral_b_start'] . '-' . $_v['integral_b_end']);
                $obj->getActiveSheet(0)->setCellValue($cellName[4] . ($i+$_row), date('Y-m-d', $_v['create_time']));
                $obj->getActiveSheet(0)->setCellValue($cellName[5] . ($i+$_row), $_v['desc']);
                $i++;
            }
        }
        //文件名处理
        $fileName = date('Y-m-d',time()).'事件列表';

        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
        //网页下载
        header('pragma:public');
        header("Content-Disposition:attachment;filename=$fileName.xlsx");
        $objWrite->save('php://output');exit;
    }

    //固定积分配置
    public function fixed()
    {
        $name = I('name', '');
        $type = I('cate_id', 0);
        if (!empty($name)) {
            $where['a.name'] = ['like', "%{$name}%"];
        }
        if (!empty($type)) {
            $where['a.cate_id'] = $type;
        }
        $com_id = $this->com_id;
        $where['a.com_id'] = $com_id;
        $export = I('export', 0);
        if ($export == 1) {
            $list_a = M('com_fixed_integral a')
                ->join('com_fixed_integral_cate b', 'a.cate_id = b.id', 'left')
                ->join('com_fixed_relation_users c', 'a.id = c.fixed_id', 'right')
                ->join('users d', 'd.id = c.user_id', 'left')
                ->join('com_department e', 'e.id = d.department_id', 'left')
                ->join('users f', 'f.id = a.user_id', 'left')
                ->where($where)
                ->field('a.*,b.name cate_name,d.name user_name,d.job_number,e.name department_name,f.name add_name')
                ->select();
            $this->fixed_export($list_a);
        }
        $list = M('com_fixed_integral a')
            ->join('com_fixed_integral_cate b', 'a.cate_id = b.id', 'left')
            ->join('com_fixed_integral_cate c', 'b.pid = c.id', 'left')
            ->join('users d', 'd.id = a.user_id', 'left')
            ->join('com_fixed_relation_users e', 'a.id=e.fixed_id', 'left')
            ->group('a.id')
            ->where($where)
            ->field('a.*,b.name cate_name,c.name p_cate_name,d.name user_name,count(DISTINCT e.id) fixed_count')
            ->paginate('', false, page_param());
        $where_1['a.com_id'] = $this->com_id;
        $list_user = M('com_fixed_integral_cate a')
            ->join('com_fixed_integral_cate b', 'b.id = a.pid', 'left')
            ->field('a.*,b.name p_name')
            ->where($where_1)->select();
        $this->assign('list_user', $list_user);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //固定积分分类
    public function fixed_cate()
    {
        $where['a.com_id'] = $this->com_id;
        $list = M('com_fixed_integral_cate a')
            ->join('com_fixed_integral_cate b', 'b.id=a.pid', 'left')
            ->field('a.*,b.name name_p')
            ->where($where)
            ->paginate('', false, page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }

    //分类编辑
    public function fixed_cate_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->fixed_cate_store($request);
        }
        $id = I('id', 0);
        $list = M('com_fixed_integral_cate')->where('id', $id)->find();
        $list_user = M('com_fixed_integral_cate')->select();
        $this->assign('list_user', $list_user);
        $this->assign('info', $list);
        return $this->fetch();
    }

    //事件分类编辑或添加提交
    public function fixed_cate_store()
    {
        
        $params = input();
//        var_dump($params);die;
        $result = $this->validate(
            $params,
            ['name' => 'require|max:50',
            ],
            ['name.require' => '标题必填',
                'name.max' => '标题最多50个字符',
            ]
        );

        if(db('com_fixed_integral_cate')->where(['name'=>$params['name'],'com_id'=>$this->com_id])->find()) return $this->ajaxReturn(1, '该分类名称已存在！');

        if(db('com_fixed_integral_cate')->where(['id'=>$params['pid'],'type'=>1])->find()) return $this->ajaxReturn(1, '上级是终极分类，不可新增下级分类');


        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if ($params['id']) {
            db('com_fixed_integral_cate')->where('id', $params['id'])->update(['name'=>$params['name']]);
        } else {
            $params['com_id'] = $this->com_id;
            db('com_fixed_integral_cate')->insert($params);
        }
        return $this->ajaxReturn(0, '成功', url(CONTROLLER_NAME . '/fixed_cate'));

    }

    //删除
    public function fixed_cate_del()
    {
        $params = input();
        $info = db('com_fixed_integral_cate')->where('pid', $params['id'])->find();
        if (!empty($info)) {
            return $this->ajaxReturn(1, '请先删除下级分类');
        }
        //查询是否有使用
        $res = M('com_fixed_integral')->where('cate_id',$params['id'])->find();
        if (!empty($res)) {
            return $this->ajaxReturn(1, '改分类有配置项目，不能删除');
        }
        $ids = explode(',', $params['id']);
        db('com_fixed_integral_cate')->where('id', 'in', $ids)->delete();
        return $this->ajaxReturn(0, '成功');
    }

    //固定积分编辑
    public function fixed_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->fixed_store($request);
        }
        $id = I('id', 0);
        $list = M('com_fixed_integral a')
            ->join('com_fixed_integral_cate b', 'b.id = a.cate_id', 'left')    
            ->field('a.*,b.name p_name')
            ->where('a.id', $id)->find();
        //用户
        $this->assign('info', $list);
        return $this->fetch();
    }

    //固定积分编辑或添加提交
    public function fixed_store()
    {
        $params = input();
//        var_dump($params);die;
        $result = $this->validate(
            $params,
            ['name' => 'require|max:50',
            ],
            ['name.require' => '标题必填',
                'name.max' => '标题最多50个字符',
            ]
        );
        if($params['id']){
            $integral = db('com_fixed_integral')->where(['name'=>$params['name'],'com_id'=>$this->com_id,'id'=>['neq',$params['id']]])->find();
            if(!empty($integral)) return $this->ajaxReturn(1, '该名称已存在！');
        }else{
            $integral = db('com_fixed_integral')->where(['name'=>$params['name'],'com_id'=>$this->com_id])->find();
            if(!empty($integral)) return $this->ajaxReturn(1, '该名称已存在！');
        }


        if(db('com_fixed_integral_cate')->where(['id'=>$params['cate_id'],'type'=>0])->find()) return $this->ajaxReturn(1, '父级别分类非是终极分类');


        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if ($params['id']) {
            db('com_fixed_integral')->where('id', $params['id'])->update($params);
        } else {
            $params['com_id'] = $this->com_id;
            $params['create_time'] = time();
            $params['user_id'] = session('user_com')['id'];
            db('com_fixed_integral')->insert($params);
        }
        return $this->ajaxReturn(0, '成功', url(CONTROLLER_NAME . '/fixed'));

    }

    //固定积分删除
    public function fixed_del(){
        $params = input();
        $ids = explode(',', $params['id']);
        $where = ['id'=>['in', $ids], 'com_id'=>$this->com_id];
        $where_relation = ['fixed_id'=>['in', $ids], 'com_id'=>$this->com_id];
        $fixed_relation = db('com_fixed_relation_users')->where($where_relation)->column('fixed_id');
        if($fixed_relation){
            return $this->ajaxReturn(1, '删除失败 已有用户关联配置');
        }
        db('com_fixed_integral')->where($where)->delete();
        return $this->ajaxReturn(0, '成功');
    }

    //固定积分人员列表
    public function fixed_user()
    {
        $id = I('id', 0);
        $list = M('com_fixed_relation_users a')
            ->join('users b', 'b.id = a.user_id', 'left')
            ->join('com_department c', 'c.id = b.department_id', 'left')
            ->where('a.fixed_id', $id)
            ->field('a.id,b.avatar,b.name,c.name department_name')
            ->paginate('', false, page_param());
        $this->assign('list', $list);
        $this->assign('id', $id);
        return $this->fetch();
    }

    //新增固定积分人员
    public function fixed_user_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->fixed_user_store($request);
        }
        $id = I('id', 0);
        $com_id = $this->com_id;
        $ids = M('com_fixed_relation_users')->where('com_id', $com_id)->where('fixed_id', $id)->column('user_id');
        $where['id'] = ['not in', $ids];
        $where['com_id'] = $com_id;
        $list = M('users')->where($where)->select();
        $this->assign('user_list', $list);
        $this->assign('id', $id);
        return $this->fetch();
    }

    //新增固定积分人员提交
    public function fixed_user_store()
    {
        $params = input();

        $result = $this->validate(
            $params,
            ['user_id' => 'require',
            ],
            ['user_id.require' => '用户id不能为空',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if(!$cfi_info = db('com_fixed_integral')->where('id', $params['id'])->find()){
            return $this->ajaxReturn(1, '非法提交，分类不存在');
        }

        if(!$cfic_info = db('com_fixed_integral_cate')->where(['id'=> $cfi_info['cate_id'], 'type'=>1])->find()){
            return $this->ajaxReturn(1, '非法提交，该分类不是终极分类');
        }

        $userIds = $params['user_id'];

        $cfru_UserIds = db('com_fixed_relation_users')->where(['com_id'=>$this->com_id, 'fixed_id'=>$params['id']])->column('user_id');

        $userIds = array_diff($userIds, $cfru_UserIds);

        $data = [];
        foreach ($userIds as $v) {
            $data[] = [
                'com_id'=>$this->com_id,
                'fixed_id'=>$params['id'],
                'user_id'=>$v
            ];
        }
        db('com_fixed_relation_users')->insertAll($data);

//        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/fixed_user', ['id' => $params['fixed_id']]));
        return $this->ajaxReturn();
    }

    //固定积分人员删除
    public function fixed_user_del()
    {
        $params = input();
        $ids = explode(',', $params['id']);
        db('com_fixed_relation_users')->where('id', 'in', $ids)->delete();
        return $this->ajaxReturn(0, '成功');
    }

    //事件库导出Excel
    public function fixed_export_1($data)
    {
        set_time_limit(0);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">类型</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">积分名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">固定积分得分</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">人员工号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">人员姓名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">机构名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">创建人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">创建时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
        $strTable .= '</tr>';
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['cate_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['integral'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['job_number'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['user_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['department_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['add_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i', $val['create_time']) . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['desc'] . '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        unset($list);
        $name = '积分管理-固定积分';
        downloadExcel($strTable, $name);
        exit();
    }
    //事件库导出Excel@stone
    public function fixed_export($list){
        set_time_limit(0);
        $key = ['类型', '积分名称', '固定积分得分', '人员工号', '人员姓名', '机构名称','创建人','创建时间','备注'];
        import('PHPExcel/PHPExcel', EXTEND_PATH);
        $obj = new \PHPExcel();
        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj->getActiveSheet(0)->setTitle(date('Y-m-d',time()).'积分管理-固定积分');   //设置sheet名称
        $_row = 1;   //设置纵向单元格标识
        $title=$key;
        if($title){
            $i = 0;
            foreach($title AS $v){   //设置列标题
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);

                $i++;
            }
            $_row++;
        }
        //设置样式
        $obj->getActiveSheet()->getStyle( 'A1:I1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        //设置背景样式
        $obj->getActiveSheet()->getStyle( 'A1:I1')->getFill()->getStartColor()->setARGB('FF808000');
        //设置单元格格式:文本
        $obj->getActiveSheet()->getStyle('B')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $obj->getActiveSheet()->getStyle('C')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $obj->getActiveSheet()->getStyle('D')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $obj->getActiveSheet()->getStyle('I')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        //设置宽度
        $obj->getActiveSheet()->getColumnDimension( 'A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'B')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'C')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'D')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'E')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'G')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'H')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension( 'I')->setWidth(20);
        //填写数据
        $val = [];
        foreach ($list as $k => $v) {
            $val[] = [
                $v['cate_name'],
                $v['name'],
                $v['integral'],
                $v['job_number'],
                $v['user_name'],
                $v['department_name'],
                $v['add_name'],
                date('Y-m-d', $v['create_time']),
                $v['desc'],
            ];
        }
        $data = $val;
        if($data){
            $i = 0;
            foreach($data AS $_v){
                foreach ($_v as $key=>$_vv){
                    $obj->getActiveSheet(0)->setCellValue($cellName[$key] . ($i+$_row), $_vv);
                }
                $i++;
            }
        }
        //文件名处理
        $fileName = date('Y-m-d',time()).'积分管理-固定积分';
        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
        //网页下载
        header('pragma:public');
        header("Content-Disposition:attachment;filename=$fileName.xlsx");
        $objWrite->save('php://output');exit;
    }

    //固定积分导入 author : zj
    public function fixed_import()
    {
        if($_FILES['file']['error'] != 0){
            return $this->ajaxReturn(1, "文件上传有误");
        }
        //文件是否大于1M
        if($_FILES['file']['size'] > 102400){
            return $this->ajaxReturn(1, "文件最大1M");
        }
        $r = action('file/controller_up');
        if($r['err'] != 0){
            return $this->ajaxReturn(1, "文件保存出错");
        }
        $path = ROOT_PATH.'public'.$r['data']['saveName'];
        $type = 'Xlsx';//设置为Xls代表支持2003或以下版本，Xlsx代表2007版
        $xlsReader = IOFactory::createReader($type);
        $xlsReader->setReadDataOnly(true);
        $Sheets = $xlsReader->load($path);
        $dataArray = $Sheets->getSheet(0)->toArray();
        unlink($path);

        $data = [];

        unset($dataArray[0]);       //删除第一行，从第二行开始读取

        foreach ($dataArray as $key=>$row){
            if(!empty($row[0])) {
                if (!$row[0]) return $this->ajaxReturn(1, '固定积分类型不能为空');
                if (!$row[1]) return $this->ajaxReturn(1, '积分名称不能为空');
                if (!$row[2]) return $this->ajaxReturn(1, '工号不能为空');
                if (!$row[3]) return $this->ajaxReturn(1, '姓名不能为空');

                if (!$user_id = db('users')->where(['job_number' => $row[2], 'type' => 1, 'name' => $row[3], 'com_id' => $this->com_id])->find()) return $this->ajaxReturn(1, $row[3] . '用户不存在或者工号对不上');

                if (!$cfi_info = db('com_fixed_integral')->where('name', $row[1])->where('com_id', $this->com_id)->find()) return $this->ajaxReturn(1, $row[1] . '该积分名称不存在！');

                if (!db('com_fixed_integral_cate')->where(['id' => $cfi_info['cate_id'], 'type' => 1, 'name' => $row[0], 'com_id' => $this->com_id])->find()) return $this->ajaxReturn(1, $row[0] . '固定积分类型不存在或非终极分类');

                if (db('com_fixed_relation_users')->where(['fixed_id' => $cfi_info['id'],'user_id' => $user_id['id'], 'com_id' => $this->com_id])->find()) return $this->ajaxReturn(1, $row[1] . '积分分类中已存在' . $row[3] . '用户');

                $data[] = [
                    'com_id' => $this->com_id,
                    'fixed_id' => $cfi_info['id'],
                    'user_id' => $user_id['id'],
                ];
            }
        }

        DB::startTrans();
        try{
            if(!empty($data)){
                M('com_fixed_relation_users')->insertAll($data);
            }
            DB::commit();
            return $this->ajaxReturn(0,'导入成功');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }

    //积分奖扣(我提交的)
    public function index()
    {
        $name = I('name', '');
        $status = I('status', -1);
        $first_check_user_id = I('first_check_user_id', 0);
        $last_check_user_id = I('last_check_user_id', 0);
        if (!empty($name)) {
            $where['a.theme'] = ['like', "%{$name}%"];
        }
        if ($status != -1) {
            $where['a.status'] = $status;
        }
        if (!empty($first_check_user_id)) {
            $where['a.first_check_user_id'] = $first_check_user_id;
        }
        if (!empty($last_check_user_id)) {
            $where['a.last_check_user_id'] = $last_check_user_id;
        }
        //奖扣时间
        $s_time = I('s_time', '');
        $e_time = I('e_time', '');
        if (!empty($s_time)) {
            $where['a.prize_buckle_time'] = ['egt', strtotime($s_time)];
        }
        if (!empty($e_time)) {
            $where['a.prize_buckle_time'] = ['elt', strtotime($e_time)];
        }
        if (!empty($s_time) && !empty($e_time)) {
            $where['a.prize_buckle_time'] = ['between', [strtotime($s_time), strtotime($e_time)]];
        }
        //记录时间
        $s_time_record = I('s_time_record', '');
        $e_time_record = I('e_time_record', '');
        if (!empty($s_time_record)) {
            $where['a.create_time'] = ['egt', strtotime($s_time_record)];
        }
        if (!empty($e_time_record)) {
            $where['a.create_time'] = ['elt', strtotime($e_time_record)];
        }
        if (!empty($s_time_record) && !empty($e_time_record)) {
            $where['a.create_time'] = ['between', [strtotime($s_time_record), strtotime($e_time_record)]];
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.record_user_id'] = $user_id;//我提交的奖扣
        $list = M('com_integral_prize_buckle a')
            ->where($where)
            ->order('a.create_time desc')
            ->paginate('', false, page_param());
        $users = M('users')->where('com_id', $com_id)->field('id,name')->select();
        $users_data = [];
        if (!empty($users)) {
            foreach ($users as $key => $value) {
                $users_data[$value['id']] = $value['name'];
            }
        }
        //审核权限的用户
        $where_2['a.com_id'] = $this->com_id;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.id,b.name,c.name department_name')
            ->where($where_2)
            ->select();
        $this->assign('users', $users_data);
        $this->assign('list', $list);
        $this->assign('list_user', $list_user);
        return $this->fetch();
    }
    //积分奖扣(我参与的)
    public function index_take()
    {
        $name = I('name', '');
        $status = I('status', -1);
        $first_check_user_id = I('first_check_user_id', 0);
        $last_check_user_id = I('last_check_user_id', 0);
        if (!empty($name)) {
            $where['d.name'] = ['like', "%{$name}%"];
        }
        if ($status != -1) {
            $where['a.status'] = $status;
        }
        if (!empty($first_check_user_id)) {
            $where['a.first_check_user_id'] = $first_check_user_id;
        }
        if (!empty($last_check_user_id)) {
            $where['a.last_check_user_id'] = $last_check_user_id;
        }
        //奖扣时间
        $s_time = I('s_time', '');
        $e_time = I('e_time', '');
        if (!empty($s_time)) {
            $where['a.prize_buckle_time'] = ['egt', strtotime($s_time)];
        }
        if (!empty($e_time)) {
            $where['a.prize_buckle_time'] = ['elt', strtotime($e_time)];
        }
        if (!empty($s_time) && !empty($e_time)) {
            $where['a.prize_buckle_time'] = ['between', [strtotime($s_time), strtotime($e_time)]];
        }
        //记录时间
        $s_time_record = I('s_time_record', '');
        $e_time_record = I('e_time_record', '');
        if (!empty($s_time_record)) {
            $where['a.create_time'] = ['egt', strtotime($s_time_record)];
        }
        if (!empty($e_time_record)) {
            $where['a.create_time'] = ['elt', strtotime($e_time_record)];
        }
        if (!empty($s_time_record) && !empty($e_time_record)) {
            $where['a.create_time'] = ['between', [strtotime($s_time_record), strtotime($e_time_record)]];
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['c.user_id'] = $user_id;//我参与的奖扣
        $list = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id = a.id','right')
            ->join('com_event d','d.id = b.event_id','left')
            ->join('com_integral_event_relation_users c','c.event_id = b.id','left')
            ->join('users u1','u1.id = a.record_user_id','left')
            ->join('users u2','u2.id = a.first_check_user_id','left')
            ->join('users u3','u3.id = a.last_check_user_id','left')
            ->where($where)
            ->group('b.id')
            ->field('a.*,d.name event_name,sum(c.integral_a) integral_a,sum(c.integral_b) integral_b, u1.name r_name, u2.name f_name, u3.name l_name')
            ->order('a.create_time desc')
            ->paginate('', false, page_param());

        //审核权限的用户
        $where_2['a.com_id'] = $this->com_id;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.id,b.name,c.name department_name')
            ->where($where_2)
            ->select();

        $this->assign('list', $list);
        $this->assign('list_user', $list_user);
        return $this->fetch();
    }
    //删除奖扣
    public function index_del(){
        $id = I('id',0);
        if(empty($id)){
            return $this->ajaxReturn(1,'id不能为空');
        }
        DB::startTrans();
        try{
            //查询奖扣事件id
            $event_ids = M('com_integral_prize_buckle_relation_event')->where('prize_buckle_id',$id)->column('id');
            //删除用户表
            M('com_integral_event_relation_users')->where('event_id','in',$event_ids)->delete();
            //删除事件表
            M('com_integral_prize_buckle_relation_event')->where('id','in',$event_ids)->delete();
            //删除积分奖扣表
            M('com_integral_prize_buckle')->where('id',$id)->delete();
            DB::commit();
            return $this->ajaxReturn(0,'撤回成功');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }
    //新增奖扣
    public function index_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->index_store($request);
        }
        $id = input('event_id',0) > 0 ? input('event_id') : I('id', 0);
        $task_id = input('task_id',0);
        //获取事件名称和事件Id
        $event = M('com_event a')
            ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
            ->join('com_event_cate c', 'c.id=b.pid', 'left')
            ->field('a.*,b.name cate_name,c.name p_cate_name')
            ->where('a.id', $id)
            ->select();
        foreach ($event as $key=>$value) {
            //负责人
            $task_a = M('com_task a')
                ->join('users b', 'b.id=a.principal_user_id', 'left')
                ->field('b.name user_name,b.id user_id')
                ->where('a.id', $task_id)
                ->select();
            //参与人
            $task_b = M('com_task_relation_take a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->where('a.task_id', $task_id)
                ->field('b.name user_name,b.id user_id')
                ->select();
            $list = array_merge($task_a, $task_b);
            $event[$key]['list'] = $list;
        }
//        var_dump($event);die;
        //部门默认审核人
        $this->get_check_people();
        $this->assign('info',$event);
        $this->assign('task_id',$task_id);
        $this->assign('task_id',$task_id);
        $this->base_department_page();
        $this->base_event_cate();
        return $this->fetch();
    }
    //新增奖扣提交
    public function index_store()
    {
        $params = input();
//        return $this->ajaxReturn(0,'','',$params);
//        return return_json(1,'',$params);die;
        $result = $this->validate(
            $params,
            [
                'theme' => 'require',
                'event_id' => 'require',
                'user_id' => 'require',
                'prize_buckle_time' => 'require',
                'first_check_user_id' => 'require',
                'last_check_user_id' => 'require',
            ],
            [
                'theme.require' => '主题不能为空',
                'user_id.require' => '参与人不能为空',
                'prize_buckle_time.require' => '奖扣时间不能为空',
                'event_id.require' => '至少选择一个事件',
                'first_check_user_id.require' => '初审人必填',
                'last_check_user_id.require' => '终审人必填',
            ]
        );
        if(empty($params['first_check_user_id'])){
            return $this->ajaxReturn(1, '初审人必填');
        }
        if(empty($params['last_check_user_id'])){
            return $this->ajaxReturn(1, '终审人必填');
        }
        if(empty($params['theme'])){
            return $this->ajaxReturn(1, '主题不能为空');
        }
        if(empty($params['event_id'])){
            return $this->ajaxReturn(1, '至少选择一个事件');
        }
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if($params['first_check_user_id'] == $params['last_check_user_id']){
            return $this->ajaxReturn(1,'初审和终审人不能是同一人');
        }

        if(count($params['event_id']) > count($params['user_id'])){
            return $this->ajaxReturn(1,'参与人不能为空');
        }
        foreach ($params['user_id'] as $key=>$value){
            if (count($value) != count(array_unique($value))){
                return $this->ajaxReturn(1,'参与人不能重复');
            }
        }

        //添加数据
        DB::startTrans();//开启事务
        try{
            //A分
            $integral_a_add = 0;
            $integral_a_del = 0;
            //B分
            $integral_b_add = 0;
            $integral_b_del = 0;
            foreach ($params['event_id'] as $key=>$value){
//                $number = $params['number'][$key];
//                var_dump($number);
//                var_dump($params['user_id'][$params['number'][$key]]);
                foreach ($params['user_id'][$params['number'][$key]] as $k=>$v){
                    $piece_rate = 1;
                    $integral_a = $params['integral_a'][$params['number'][$key]][$k]??0;
                    $integral_b = $params['integral_b'][$params['number'][$key]][$k]??0;
                    $piece_rate = $params['piece_rate'][$params['number'][$key]][$k]??1;
//                    var_dump($piece_rate);
                    $aa = (int)$integral_a * (int)$piece_rate;
                    $bb = (int)$integral_b * (int)$piece_rate;
                    if($integral_a > 0){
                        $integral_a_add += $aa;
                    }else{
                        $integral_a_del += $aa;
                    }
                    if($integral_b > 0){
                        $integral_b_add += $bb;
                    }else{
                        $integral_b_del += $bb;
                    }
                }
            }
            //人次
            $people_sum = 0;
            foreach ($params['user_id'] as $key=>$value){
                $people_sum += count($value);
            }
//            echo 1;die;
            $data_array_1=[
                'com_id'=>$this->com_id,
                'first_check_user_id'=>$params['first_check_user_id'],
                'last_check_user_id'=>$params['last_check_user_id'],
                'record_user_id'=>session('user_com')['id'],
                'copy_user_id'=>$params['copy_user_id'],
                'prize_buckle_time'=>strtotime($params['prize_buckle_time']),
                'integral_a_add'=>$integral_a_add,
                'integral_a_del'=>$integral_a_add,
                'integral_b_add'=>$integral_b_add,
                'integral_b_del'=>$integral_b_del,
                'theme'=>$params['theme'],
                'create_time'=>time(),
                'people_sum'=>$people_sum,
                'desc'=>$params['desc'],
            ];
            //初审人和记录人相同跳过初审
            if($params['first_check_user_id'] == session('user_com')['id']){
                $data_array_1['status'] = 1;
                $data_array_1['first_check_time'] = time();
            }else{
                $data_array_1['status'] = 0;
            }

            //添加主题数据
            if(empty($params['id'])){
                $theme_id = M('com_integral_prize_buckle')->insertGetId($data_array_1);
            }else{
                $theme_id = $params['id'];
                //更新主题
                M('com_integral_prize_buckle')->where('id',$theme_id)->update($data_array_1);
                //删除事件
                $event_ids = M('com_integral_prize_buckle_relation_event')->where('prize_buckle_id',$theme_id)->column('id');
                M('com_integral_prize_buckle_relation_event')->where('prize_buckle_id',$theme_id)->delete();
                //删除参与人
                M('com_integral_event_relation_users')->where('event_id','in',$event_ids)->delete();
            }
            //添加事件数据
            foreach ($params['event_id'] as $key=>$value){
                $data_array_2 = [
                    'com_id'=>$this->com_id,
                    'prize_buckle_id'=>$theme_id,
                    'event_id'=>$value,
                    'event_desc'=>$params['event_desc'][$key],
                    'create_time'=>time(),
                ];
                $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_2);
                $event_info = M('com_event')->where('id',$value)->find();
                //添加参与人
                foreach ($params['user_id'][$params['number'][$key]] as $k=>$v){
                    $integral_a = isset($params['integral_a'][$params['number'][$key]][$k])?$params['integral_a'][$params['number'][$key]][$k]:0;
                    $integral_b = isset($params['integral_b'][$params['number'][$key]][$k])?$params['integral_b'][$params['number'][$key]][$k]:0;
                    $piece_rate = isset($params['piece_rate'][$params['number'][$key]][$k])?$params['piece_rate'][$params['number'][$key]][$k]:1;
                    $data_array_3=[
                        'com_id'=>$this->com_id,
                        'event_id'=>$event_id,
                        'user_id'=>$v,
                        'integral_a'=>$integral_a,
                        'integral_b'=>$integral_b,
                    ];
                    if($event_info['is_piece'] == 1){
                        $data_array_3['piece_rate'] = $piece_rate;
                    }//计件事件
                    if($event_info['is_lottery_ticket'] == 1){
                        $data_array_3['is_lottery_ticket'] = 1;
                    }//奖票事件
                    M('com_integral_event_relation_users')->insert($data_array_3);
                }
            }

            //发送消息
            $data_message = [];
            if(isset($data_array_1['status'])&&$data_array_1['status'] == 1){
                //终审人
                $data_message[] = [
                    'title' => '您有一条积分奖扣待审核(终审)',
                    'user_id' => $params['last_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//
                    'relation_id' => $theme_id
                ];
            }else{
                //初审人
                $data_message[] = [
                    'title' => '您有一条积分奖扣待审核(初审)',
                    'user_id' => $params['first_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//
                    'relation_id' => $theme_id
                ];
            }
            //判断是否任务提交
            if(isset($params['task_id']) && !empty($params['task_id'])){
                //修改任务状态(已提交)
                M('com_task')->where('id',$params['task_id'])->update(['status'=>4]);
            }
            Message::send_message_list($data_message);
            DB::commit();//提交
            return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/index'));
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }
    //新增奖扣
    public function index_check_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->index_check_store($request);
        }
        $id = I('id', 0);
        //审核权限的用户
        $where_2['a.com_id'] = $this->com_id;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.id,b.name,c.name department_name')
            ->where($where_2)
            ->select();
        //用户
        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->field('a.id,a.name,b.name department_name')
            ->where('a.com_id',$this->com_id)
            ->select();
        //事件
        $where_1['a.com_id'] = $this->com_id;
        $where_1['a.type'] = 1;//正式库
        $where_1['a.is_check'] = 1;//专审事件
        $event = M('com_event a')
            ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
            ->join('com_event_cate c', 'c.id=b.pid', 'left')
            ->field('a.*,b.name cate_name,c.name p_cate_name')
            ->where($where_1)->select();
        $this->assign('users', $users);
        $this->assign('list_user', $list_user);
        $this->assign('event', $event);
        $this->assign('id', $id);
        $this->assign('info', []);
        $this->base_event_cate();       //事件列表
        $this->base_department_page();       //部门列表

        return $this->fetch();
    }
    public function get_event(){
        $id = I('id',0);
        $event = M('com_event')->where('id',$id)->field('first_check_user_id,last_check_user_id')->find();
        return $this->ajaxReturn(0,'获取成功','',$event);
    }

    //新增奖扣提交
    public function index_check_store()
    {
//        echo 1;die;
        $params = input();
//        var_dump($params);die;
        $result = $this->validate(
            $params,
            [
                'theme' => 'require',
                'user_id' => 'require',
                'prize_buckle_time' => 'require',
            ],
            [
                'theme.require' => '主题不能为空',
                'user_id.require' => '参与人不能为空',
                'prize_buckle_time.require' => '奖扣时间不能为空',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if($params['first_check_user_id'] == $params['last_check_user_id']){
            return $this->ajaxReturn(1,'初审和终审人不能是同一人');
        }
//        $params['first_check_user_id'] = $params['first_check_user_id_a'];
//        $params['last_check_user_id'] = $params['last_check_user_id_a'];
        if(count($params['event_id']) > count($params['user_id'])){
            return $this->ajaxReturn(1,'参与人不能为空');
        }

        if(is_array($params['user_id'])) {
            if (count($params['user_id']) != count(array_unique($params['user_id']))) {
                return $this->ajaxReturn(1, '参与人不能重复');
            }
        }

        //添加数据
        DB::startTrans();//开启事务
        try{
            //A分

            $integral_a_add = 0;
            $integral_a_del = 0;
            //B分
            $integral_b_add = 0;
            $integral_b_del = 0;
            foreach ($params['event_id'] as $key=>$value){
                foreach ($params['user_id'] as $k=>$v){
                    $integral_a = isset($params['integral_a'][$k])?$params['integral_a'][$k]:0;
                    $integral_b = isset($params['integral_b'][$k])?$params['integral_b'][$k]:0;
                    $piece_rate = isset($params['piece_rate'][$k])?$params['piece_rate'][$k]:1;
                    if($integral_a > 0){
                        $integral_a_add += (int)$integral_a *$piece_rate;
                    }else{
                        $integral_a_del += (int)$integral_a *$piece_rate;
                    }
                    if($integral_b > 0){
                        $integral_b_add += (int)$integral_b *$piece_rate;
                    }else{
                        $integral_b_del += (int)$integral_b *$piece_rate;
                    }
                }
            }
            //人次
            $people_sum = count($params['user_id']);
//            $people_sum = 0;
//            foreach ($params['user_id'] as $key=>$value){
//                $people_sum += count($value);
//            }
            $data_array_1=[
                'com_id'=>$this->com_id,
                'first_check_user_id'=>$params['first_check_user_id'],
                'last_check_user_id'=>$params['last_check_user_id'],
                'record_user_id'=>session('user_com')['id'],
                'copy_user_id'=>$params['copy_user_id'],
                'prize_buckle_time'=>strtotime($params['prize_buckle_time']),
                'integral_a_add'=>$integral_a_add,
                'integral_a_del'=>$integral_a_add,
                'integral_b_add'=>$integral_b_add,
                'integral_b_del'=>$integral_b_del,
                'theme'=>$params['theme'],
                'create_time'=>time(),
                'people_sum'=>$people_sum,
                'desc'=>$params['desc'],
            ];
            //初审人和记录人相同跳过初审
            if($params['first_check_user_id'] == session('user_com')['id']){
                $data_array_1['status'] = 1;
                $data_array_1['first_check_time'] = time();
            }

            //添加主题数据
            $theme_id = M('com_integral_prize_buckle')->insertGetId($data_array_1);
            //添加事件数据
            foreach ($params['event_id'] as $key=>$value){
                $data_array_2 = [
                    'com_id'=>$this->com_id,
                    'prize_buckle_id'=>$theme_id,
                    'event_id'=>$value,
                    'event_desc'=>$params['event_desc'][$key],
                    'create_time'=>time(),
                ];
                $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_2);
                $event_info = M('com_event')->where('id',$value)->find();
                //添加参与人
                foreach ($params['user_id'] as $k=>$v){
                    $integral_a = isset($params['integral_a'][$k])?$params['integral_a'][$k]:0;
                    $integral_b = isset($params['integral_b'][$k])?$params['integral_b'][$k]:0;
                    $piece_rate = isset($params['piece_rate'][$k])?$params['piece_rate'][$k]:1;
                    $data_array_3=[
                        'com_id'=>$this->com_id,
                        'event_id'=>$event_id,
                        'user_id'=>$v,
                        'integral_a'=>$integral_a,
                        'integral_b'=>$integral_b,
                    ];
                    if($event_info['is_piece'] == 1){
                        $data_array_3['piece_rate'] = $piece_rate;
                    }//计件事件
                    if($event_info['is_lottery_ticket'] == 1){
                        $data_array_3['is_lottery_ticket'] = 1;
                    }//奖票事件
                    M('com_integral_event_relation_users')->insert($data_array_3);
                }
            }
            //发送消息
            $data_message = [];
            if(isset($data_array_1['status'])&&$data_array_1['status'] == 1){
                //终审人
                $data_message[] = [
                    'title' => '您有一条积分奖扣待审核(终审)',
                    'user_id' => $params['last_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//
                    'relation_id' => $theme_id
                ];
            }else{
                //初审人
                $data_message[] = [
                    'title' => '您有一条积分奖扣待审核(初审)',
                    'user_id' => $params['first_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//
                    'relation_id' => $theme_id
                ];
            }
            Message::send_message_list($data_message);
            DB::commit();//提交
            return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/index'));
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }

    public function leave()
    {
        $name = I('name', '');
        $status = I('status', 0);
        $s_time = I('s_time', '');
        $e_time = I('e_time', '');
        if (!empty($s_time)) {
            $where['a.start_time'] = ['egt', strtotime($s_time)];
        }
        if (!empty($e_time)) {
            $where['a.start_time'] = ['elt', strtotime($e_time)];
        }
        if (!empty($s_time) && !empty($e_time)) {
            $where['a.start_time'] = ['between', [strtotime($s_time), strtotime($e_time)]];
        }
        if (!empty($name)) {
            $where['b.name|b.job_number'] = ['like', "%{$name}%"];
        }
        if (!empty($status)) {
            $where['a.type'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.user_id'] = $user_id;//请假者
        $list = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('users c', 'c.id=a.first_check_user_id', 'left')
            ->join('users d', 'd.id=a.last_check_user_id', 'left')
            ->where($where)
            ->order('a.id desc')
            ->field('a.*,b.name b_name,b.job_number,c.name c_name,d.name d_name')
            ->paginate('', false, page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }
    //新增请假
    public function leave_edit(Request $request)
    {
        //系统配置提醒
        $config = M('com_config')->where('com_id',$this->com_id)->find();
        $this->assign('config',$config);
        //固定积分
        $where = [];
        $where['a.com_id'] = $this->com_id;
        $where['b.user_id'] =$this->user_id;
        $fixed_deduct_sum = M('com_fixed_integral a')
            ->join('com_fixed_relation_users b','b.fixed_id=a.id','right')
            ->where($where)
            ->sum('a.integral');
        $fixed_deduct_day = (int)ceil($fixed_deduct_sum);
        $this->assign('fixed_deduct_day',$fixed_deduct_day);
        if ($request->isPost()) {
            return $this->leave_store($request);
        }
        $id = I('id', 0);

        $info = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('users c', 'c.id=a.first_check_user_id', 'left')
            ->join('users d', 'd.id=a.last_check_user_id', 'left')
            ->join('com_department e','e.id=b.department_id','left')
            ->join('com_department f','f.id=c.department_id','left')
            ->join('com_department g','g.id=d.department_id','left')
            ->where('a.com_id', $this->com_id)
            ->where('a.id', $id)
            ->field('a.*,b.name b_name,b.job_number,c.name c_name,d.name d_name, e.name b_department_name,f.name c_department_name,g.name d_department_name')
            ->find();
        $this->assign('info', $info);
        $this->get_check_people();//默认审核人
        $this->base_department_page();//部门列表

        return $this->fetch();
    }

    //新增请假提交
    public function leave_store()
    {
        $params = input();

        if(!empty($params['start_time'])){
            $params['start_time'] = strtotime($params['start_time']);
            if($params['start_time']< time()){
                return $this->ajaxReturn(1,'请假时间不能小于当前时间');
            }
        }else{
            return $this->ajaxReturn(1,'请假时间不能为空');
        }
        if(empty($params['id'])){
            $params['com_id'] = $this->com_id;
            $params['create_time'] = time();
            if($this->user_id == $params['first_check_user_id']){
//                $params['first_check_opinion'] = $params['check_opinion']??'';
                $params['status'] = 1;
                $params['first_check_time'] = time();
            }
            db('com_leave')->insert($params);
        }else{
            $params['status'] = 0;
            if($this->user_id == $params['first_check_user_id']){
                $params['first_check_opinion'] = $params['check_opinion']??'';
                $params['status'] = 1;
                $params['first_check_time'] = time();
            }

            db('com_leave')->where('id', $params['id'])->update($params);

            //审核，后续事件
            if($params['status'] == 1) {
                $user_id = $params['last_check_user_id'];
                $title = '您有请假记录待审核(终审)';
            }else{
                $user_id = $params['first_check_user_id'];
                $title = '您有请假记录待审核(初审)';
            }

            \app\company\logic\Message::send_message($title, $user_id, 1, 4, $params['id']);

        }

        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/leave'));
    }
    //查看请假详情
    public function leave_info(){
        $id = I('id', 0);

        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->field('a.id,a.name,b.name department_name')
            ->where('a.com_id',$this->com_id)->select();

        $info = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('users c', 'c.id=a.first_check_user_id', 'left')
            ->join('users d', 'd.id=a.last_check_user_id', 'left')
            ->join('com_department e','e.id=b.department_id','left')
            ->join('com_department f','f.id=c.department_id','left')
            ->join('com_department g','g.id=d.department_id','left')
            ->where('a.com_id', $this->com_id)
            ->where('a.id', $id)
            ->field('a.*,b.name b_name,b.job_number,c.name c_name,d.name d_name, e.name b_department_name,f.name c_department_name,g.name d_department_name')
            ->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    public function leave_check()
    {
        $name = I('name', '');
        $status = I('status', 0);
        $s_time = I('s_time', '');
        $e_time = I('e_time', '');
        if (!empty($s_time)) {
            $where['a.start_time'] = ['egt', strtotime($s_time)];
        }
        if (!empty($e_time)) {
            $where['a.start_time'] = ['elt', strtotime($e_time)];
        }
        if (!empty($s_time) && !empty($e_time)) {
            $where['a.start_time'] = ['between', [strtotime($s_time), strtotime($e_time)]];
        }
        if (!empty($name)) {
            $where['b.name|b.job_number'] = ['like', "%{$name}%"];
        }
        if (!empty($status)) {
            $where['a.type'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['first_check_user_id|last_check_user_id'] = $user_id;//审核者
        $list = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('users c', 'c.id=a.first_check_user_id', 'left')
            ->join('users d', 'd.id=a.last_check_user_id', 'left')
            ->where($where)
            ->order('a.create_time desc')
            ->field('a.*,b.name b_name,b.job_number,c.name c_name,d.name d_name')
            ->paginate('', false, page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }

    //请假审核
    public function leave_check_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->leave_check_store($request);
        }
        $id = I('id', 0);
        //审核权限的用户
        $where_1['a.com_id'] = $this->com_id;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.id,b.name,c.name department_name')
            ->where($where_1)->select();
        //用户
        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->field('a.id,a.name,b.name department_name')
            ->where('a.com_id',$this->com_id)->select();
        $this->assign('users',$users);
        $this->assign('list_user',$list_user);
        $info = M('com_leave')->where('id',$id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 我的积分
     */
    public function myinte(){
        //前一个月 查询的月份 后一个月
        $nowDateStr = date("Y-m");
        $queryMonthStr = input('ndate', $nowDateStr, 'addslashes');//当前要查询的时间字符串
        $queryMonthInt = strtotime($queryMonthStr);
        $queryYearMonth = explode('-', $queryMonthStr);//当前要查询的时间年和月数组
        $r = preg_match("/\d{4}-\d{2}/", $queryMonthStr);
        if(!$r || $queryYearMonth[1] <1 || $queryYearMonth[1] > 12){
            $this->error('时间有误');
        }
        $lYearMonth = date('Y-m', strtotime("-1month", $queryMonthInt)); //前一个月
        $rYearMonth = date('Y-m', strtotime("+1month", $queryMonthInt)); //后一个月
        $nowDateArr = explode('-', $nowDateStr);
        $lYearMonthArr = explode('-', $lYearMonth);
        //判断是否还有前一个月
        if($lYearMonthArr[0] > $nowDateArr[0] || ($lYearMonthArr[0] >= $nowDateArr[0] && $lYearMonthArr[1] >= $nowDateArr[1])){
            $lYearMonth = '';
        }
        $rYearMonthArr = explode('-', $rYearMonth);
        //判断是否还有下一个月
        if($rYearMonthArr[0] > $nowDateArr[0] || $rYearMonthArr[1] >= $nowDateArr[1]){
            $rYearMonth = '';
        }
        if(!$lYearMonth && !$rYearMonth){
            $queryMonthStr = $nowDateStr;
            $queryYearMonth = explode('-', $queryMonthStr);//查询年和月数组
        }

        $yearMonthList = $this->myinteYearMonth($queryYearMonth);
        $trendList = $this->myinteTrend($queryYearMonth);
        $tabList = $this->myinteTab($queryYearMonth);

//        dump($tabList);die;

        $data = [
            'lYearMonth'=>$lYearMonth, //前一个月
            'queryMonthStr'=>$queryMonthStr, //当前查询月
            'rYearMonth'=>$rYearMonth, //后一个月
            'yearMonthList'=>$yearMonthList, //指定年和月的各种奖扣统计
            'trendList'=>$trendList, //折线图数据
            'tabList'=>$tabList, //获取tab切换中的 固定积分 奖扣任务 其他得分
        ];
        $this->assign($data);
        return $this->fetch();
    }

    /**
     * 查询指定年和月的各种奖扣统计
     * @param $queryYearMonth 要查询的年和月数组
     * @return array 返回折线图上面的统计数据
     */
    private function myinteYearMonth($queryYearMonth){
        $returnData = [
            'monthJiangFen'=>0, //月度奖分
            'monthKouFen'=>0, //月度扣分
            'rChang'=>0, //月份日常积分
            'guDing'=>0, //月份固定积分
            'qiTa'=>0, //月份其他得分
//            'rChangPercent'=>0, //月份日常积分百分比
//            'guDingPercent'=>0, //月份固定积分百分比
//            'qiTaPercent'=>0, //月份其他得分百分比
            'integral_a_total'=>0, //月份的A分得分
            'shangMonthFen'=>0, //上月积分
            'shangMonthAFen'=>0, //上月A分
            'leiJiFen'=>0, //累计积分
            'leiJiLevel'=>0, //累计排名
            'yearFen'=>0, //年度积分
            'yearLevel'=>0, //年度排名
            'monthFen'=>0, //月度积分
            'monthLevel'=>0, //月度排名
        ];
        $uId = session("user_com.id");//用户id
        //累计积分
        $t_s = db('users')
            ->where('com_id',$this->com_id)
            ->where('type',1)
            ->column('id,integral_b+base_integral+working_age_integral as sum');
        arsort($t_s);
        $t = array_search($uId, array_keys($t_s));
        if(is_numeric($t)) $t += 1;
        $returnData['leiJiFen'] = $t_s[$uId];
        $returnData['leiJiLevel'] = $t;
        //年度积分
        $start_time = strtotime($queryYearMonth[0].'-01'.'-01');
        $end_time = strtotime('+1 year',$start_time)-1;
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['a.com_id'] = $this->com_id;
        $where_1['d.type'] = 1;
//        $where_1['c.user_id'] = $this->user_id; //用户自己的积分
//        var_dump($where_1);die;
        $y_s = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->join('users d','d.id=c.user_id','left')
            ->group('c.user_id')
            ->where($where_1)
//            ->select();
            ->column('c.user_id,COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) integral_b_add');
        if(!array_search($uId, array_keys($y_s))){
            $y_s[$uId] = 0;
        }
        arsort($y_s);
        $y = array_search($uId, array_keys($y_s));
        if(is_numeric($y)) $y += 1;

//        $listYear = db('com_integral_log')
//            ->where(['com_id'=>$this->com_id, 'year'=>$queryYearMonth[0],'type'=>0])
//            ->group('user_id')
//            ->order('integral_b desc')
//            ->column('user_id, sum(integral_b) as integral_b, id');
//        $index = 0;//排名
//        foreach($listYear as $k=>$v){
//            $index++;
//            if($v['user_id'] == $uId){
//                break;
//            }
//        }
        $returnData['yearFen'] = $y_s[$uId];
        $returnData['yearLevel'] = $y;
        //月度积分
        $start_time = strtotime($queryYearMonth[0].'-'.$queryYearMonth[1].'-01');
        $end_time = strtotime('+1 month',$start_time)-1;
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['a.com_id'] = $this->com_id;
        $where_1['d.type'] = 1;
        $m_s = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->join('users d','d.id=c.user_id','left')
            ->group('c.user_id')
            ->where($where_1)
            ->column('c.user_id,COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) integral_b_add');
        if(!array_search($uId, array_keys($m_s))){
            $m_s[$uId] = 0;
        }
        arsort($m_s);
        $m = array_search($uId, array_keys($m_s));
        if(is_numeric($m)) $m += 1;
        $returnData['monthFen'] = $m_s[$uId];
        $returnData['monthLevel'] = $m;
        //月度积分奖分 扣分 日常 固定 其他得分
        $start_time = strtotime($queryYearMonth[0].'-'.$queryYearMonth[1].'-01');
        $end_time = strtotime('+1 month',$start_time)-1;
        $where_1 = [];
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['a.com_id'] = $this->com_id;
        $where_1['c.user_id'] = $this->user_id; //用户自己的积分
        $monthFen = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->group('c.user_id')
            ->where($where_1)
            ->field('
            COALESCE(sum(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_add,
            COALESCE(sum(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_del,
            COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) integral_b,
            COALESCE(sum(IF(c.piece_rate=0,c.integral_a,c.integral_a*c.piece_rate)),0) integral_a
            ')
            ->find();
        $returnData['integral_a_total'] = $monthFen['integral_a'];
        $returnData['monthJiangFen'] = $monthFen['integral_b_add'];
        $returnData['monthKouFen'] = $monthFen['integral_b_del'];
        $returnData['rChang'] = $monthFen['integral_b'];
        $monthFen = db('com_integral_log')
            ->where(['user_id'=>$uId, 'year'=>$queryYearMonth[0], 'month'=>$queryYearMonth[1]])
            ->column('id, type, integral_a, integral_b');
        foreach($monthFen as $k=>$v){
            switch ($v['type']){
                case 1:
                    $returnData['guDing'] += $v['integral_b'];
                    break;
                case 3:
                    $returnData['qiTa'] += $v['integral_b'];
                    break;
            }
        }
        //上月数据
        $start_time = strtotime($queryYearMonth[0].'-'.$queryYearMonth[1].'-01');
        $start_time = strtotime('-1 month',$start_time);
        $end_time = strtotime('+1 month',$start_time)-1;
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['a.com_id'] = $this->com_id;
        $where_1['c.user_id'] = $this->user_id; //用户自己的积分
        $monthFen = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->group('c.user_id')
            ->where($where_1)
            ->field('
            COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) integral_b,
            COALESCE(sum(IF(c.piece_rate=0,c.integral_a,c.integral_a*c.piece_rate)),0) integral_a
            ')
            ->find();
        $returnData['shangMonthFen'] = $monthFen['integral_b'];
        $returnData['shangMonthAFen'] = $monthFen['integral_a'];
        $count = 0;
        if($returnData['rChang'] != 0){
            $count ++;
        }else{
            $returnData['rChangPercent'] = 0;
        }
        if($returnData['guDing'] != 0){
            $count ++;
        }else{
            $returnData['guDingPercent'] = 0;
        }
        if($returnData['qiTa'] != 0){
            $count ++;
        }else{
            $returnData['qiTaPercent'] = 0;
        }
        if($count == 0){
            return $returnData;
        }elseif($count == 1){
            if(!isset($returnData['rChangPercent'])){
                $returnData['rChangPercent']  = 100;
            }
            if(!isset($returnData['guDingPercent'])){
                $returnData['guDingPercent']  = 100;
            }
            if(!isset($returnData['qiTaPercent'])){
                $returnData['qiTaPercent']  = 100;
            }
        }else{
            $sum = abs($returnData['rChang']) + abs($returnData['guDing']) + abs($returnData['qiTa']);
            if(!isset($returnData['rChangPercent'])){
                $returnData['rChangPercent']  = round(abs($returnData['rChang'])/$sum,2)*100;
            }
            if(!isset($returnData['guDingPercent'])){
                $returnData['guDingPercent']  = round(abs($returnData['guDing'])/$sum,2)*100;
            }
            if(!isset($returnData['qiTaPercent'])){
                $returnData['qiTaPercent']  = round(abs($returnData['qiTa'])/$sum,2)*100;
            }
        }
        return $returnData;
    }

    /**
     * 查询指定月的奖扣趋势折线图数据
     * @param $queryYearMonth 要查询的年和月数组
     * @return array 返回折线图数据
     */
    private function myinteTrend($queryYearMonth){
        $list = db('com_integral_log')
            ->where(['user_id'=>session("user_com.id"), 'year'=>$queryYearMonth[0], 'month'=>$queryYearMonth[1]])
            ->field('type, integral_a, integral_b, create_time')
            ->select();
        foreach($list as $k=>$v){
            $list[$k]['day'] = date('d', $v['create_time']);//
        }
        $yearDayNum = date("t",strtotime("{$queryYearMonth[0]}-{$queryYearMonth[1]}"));//该月有多少天
        $returnData = [
            'dayNum'=>[], //天数
            'jiangFen'=>[], //奖分
            'kouFen'=>[], //扣分
        ];
        //遍历当月的天数 计算各天的奖扣分
        for($i=1; $i<=$yearDayNum; $i++){
            $returnData['dayNum'][$i] = $i;
            $returnData['jiangFen'][$i] = 0;
            $returnData['kouFen'][$i] = 0;
            foreach($list as $k=>$v){
                if($v['day'] == $i){
                    if($v['integral_b'] > 0){
                        $returnData['jiangFen'][$i] += $v['integral_b'];
                    }elseif($v['integral_b'] < 0){
                        $returnData['kouFen'][$i] += $v['integral_b'];
                    }
                    unset($list[$k]);
                }
            }
        }
        $f1 = [
            'dayNum'=>[], //天数
            'jiangFen'=>[], //奖分
            'kouFen'=>[], //扣分
        ];
        //图表js需要从0开始的数组下标
        for($i=1; $i<=$yearDayNum; $i++){
            $f1['dayNum'][] = $returnData['dayNum'][$i];
            $f1['jiangFen'][] = $returnData['jiangFen'][$i];
            $f1['kouFen'][] = $returnData['kouFen'][$i];
        }
        $returnData = $f1;
        return $returnData;
    }

    /**
     * 获取tab切换中的 固定积分 奖扣任务 其他得分
     * @param $queryYearMonth 要查询的年和月数组
     * @return array
     */
    private function myinteTab($queryYearMonth){
        $returnDate = [
            'guDing'=>[], //固定积分列表
            'jiangKou'=>[], //奖扣任务列表
            'qiTa'=>[],//其他得分
        ];
        //固定积分列表
        $returnDate['guDing'] = db('com_integral_log')->alias('il')
            ->join('com_fixed_integral fi', 'fi.id=il.fixed_id', 'LEFT')
            ->field('fi.name, fi.integral, il.integral_b')
            ->where(['il.user_id'=>session("user_com.id"), 'il.type'=>1, 'il.year'=>$queryYearMonth[0], 'il.month'=>$queryYearMonth[1]])
            ->order('il.create_time desc')
            ->select();

        //奖扣任务b author:zj
        $returnDate['jiangKou'] = $this->reward_libaray_jk(strtotime($queryYearMonth[0].'-'.$queryYearMonth[1]),$this->user_id);    //传事件戳
        $returnDate['jiangKou']['ym'] = $queryYearMonth[0].'-'.$queryYearMonth[1];    //传事件戳
        //奖扣任务e author:zj

        //其他得分
        $leave_type = [0=>'其他', 1=>'事假', 2=>'病假', 3=>'旷工', 4=>'少休', 5=>'全勤'];
        $returnDate['qiTa'] = db('com_integral_log')
            ->where(['user_id'=>session("user_com.id"), 'type'=>3, 'year'=>$queryYearMonth[0], 'month'=>$queryYearMonth[1]])
            ->field('leave_type, sum(integral_b) as integral_b')
            ->group('leave_type')
            ->select();
        foreach($returnDate['qiTa'] as $k=>$v){
            $returnDate['qiTa'][$k]['leave_type'] = $leave_type[$v['leave_type']];
        }
        return $returnDate;
    }


    /**
     * 我的积分 日常奖扣
     * @return \think\response\Json
     */
    public function myinteTabRChang(){
        $queryDate = explode('-', input('queryDate', date('Y-m'), 'addslashes'));
        count($queryDate) != 2 && die;
        $u_id = session("user_com.id");
        $p = input('p', 1, 'intval');
        $count = db('com_integral_log')->alias('il')
            ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=il.event_id', 'LEFT')
            ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
            ->join('com_integral_prize_buckle ipb', 'ipb.id=ipbre.prize_buckle_id', 'LEFT')
            ->field([
                'il.id', 'il.create_time', 'il.integral_a', 'il.integral_b',
                'e.id'=>'e_id', 'e.name',
                'ipb.first_check_user_id', 'ipb.last_check_user_id'
            ])
            ->where(['il.user_id'=>$u_id, 'il.year'=>$queryDate[0], 'il.month'=>$queryDate[1],'il.type'=>0])
            ->count();
        $list = db('com_integral_log')->alias('il')
            ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=il.event_id', 'LEFT')
            ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
            ->join('com_integral_prize_buckle ipb', 'ipb.id=ipbre.prize_buckle_id', 'LEFT')
            ->field([
                'il.id', 'il.create_time', 'il.integral_a', 'il.integral_b',
                'e.id'=>'e_id', 'e.name',
                'ipb.id'=>'ipb_id', 'ipb.first_check_user_id', 'ipb.last_check_user_id'
            ])
            ->where(['il.user_id'=>$u_id, 'il.year'=>$queryDate[0], 'il.month'=>$queryDate[1],'il.type'=>0])
            ->order('il.create_time desc')
            ->page($p, 11)->select();
        $user_ids = array_merge(array_column($list, 'first_check_user_id'), array_column($list, 'last_check_user_id'));
        $user_ids = array_unique($user_ids);
        $user_list = db('users')->where(['id'=>['in', $user_ids]])->column('id, name');
        foreach($list as $k=>$v){
            $list[$k]['create_time'] = date('Y-m-d', $list[$k]['create_time']);
            $list[$k]['first_check_user_name'] = isset($user_list[$list[$k]['first_check_user_id']]) ? $user_list[$list[$k]['first_check_user_id']] : '';
            $list[$k]['last_check_user_name'] = isset($user_list[$list[$k]['last_check_user_id']]) ? $user_list[$list[$k]['last_check_user_id']] : '';
        }
        return json(['list'=>$list, 'count'=>$count]);
    }

    public function event_info(){
        $id = I('id',0);
        if(empty($id)){
            return $this->error('主题id不能为空');
        }
        //主题
        $theme = M('com_integral_prize_buckle a')
            ->join('users b','b.id = a.first_check_user_id','left')
            ->join('users c','c.id = a.last_check_user_id','left')
            ->join('users d','d.id = a.record_user_id','left')
            ->field('a.*,b.name b_name,c.name c_name,d.name d_name')
            ->where('a.id',$id)->find();
        //事件
        $event = M('com_integral_prize_buckle_relation_event a')
            ->join('com_event b','b.id=a.event_id','left')
            ->join('com_event_cate d','d.id=b.cate_id','left')
            ->join('com_integral_event_relation_users c','c.event_id = a.id','left')
            ->field('a.*,sum(c.integral_a) integral_a,sum(c.integral_b) integral_b,b.*,a.id id,d.name cate_name')
            ->group('a.id')
            ->where('a.prize_buckle_id',$id)->select();
        //参与人
        foreach ($event as $key=>$value){
            $users = M('com_integral_event_relation_users a')
                ->join('users b','b.id=a.user_id','left')
                ->where('a.event_id',$value['id'])
                ->field('a.*,b.name user_name')
                ->select();
            $event[$key]['user_list'] = $users;
        }
        //查询记录人奖励分数
//        $integral = M('com_config')->where('com_id',$this->com_id)->value('day_add_integral');
//        $this->assign('integral', $integral);
        $this->assign('theme', $theme);
        $this->assign('event', $event);
        return $this->fetch();
    }
    public function event_info_2021(){
        $id = I('id',0);
        if(empty($id)){
            return $this->error('主题id不能为空');
        }
        //主题
        $theme = M('com_integral_prize_buckle_2021 a')
            ->join('users b','b.id = a.first_check_user_id','left')
            ->join('users c','c.id = a.last_check_user_id','left')
            ->join('users d','d.id = a.record_user_id','left')
            ->field('a.*,b.name b_name,c.name c_name,d.name d_name')
            ->where('a.id',$id)->find();
        //事件
        $event = M('com_integral_prize_buckle_relation_event_2021 a')
            ->join('com_event b','b.id=a.event_id','left')
            ->join('com_event_cate d','d.id=b.cate_id','left')
            ->join('com_integral_event_relation_users_2021 c','c.event_id = a.id','left')
            ->field('a.*,sum(c.integral_a) integral_a,sum(c.integral_b) integral_b,b.*,a.id id,d.name cate_name')
            ->group('a.id')
            ->where('a.prize_buckle_id',$id)->select();
        //参与人
        foreach ($event as $key=>$value){
            $users = M('com_integral_event_relation_users_2021 a')
                ->join('users b','b.id=a.user_id','left')
                ->where('a.event_id',$value['id'])
                ->field('a.*,b.name user_name')
                ->select();
            $event[$key]['user_list'] = $users;
        }
        //查询记录人奖励分数
//        $integral = M('com_config')->where('com_id',$this->com_id)->value('day_add_integral');
//        $this->assign('integral', $integral);
        $this->assign('theme', $theme);
        $this->assign('event', $event);
        return $this->fetch('event_info');
    }
    public function event_info_2022(){
        $id = I('id',0);
        if(empty($id)){
            return $this->error('主题id不能为空');
        }
        //主题
        $theme = M('com_integral_prize_buckle_2022 a')
            ->join('users b','b.id = a.first_check_user_id','left')
            ->join('users c','c.id = a.last_check_user_id','left')
            ->join('users d','d.id = a.record_user_id','left')
            ->field('a.*,b.name b_name,c.name c_name,d.name d_name')
            ->where('a.id',$id)->find();
        //事件
        $event = M('com_integral_prize_buckle_relation_event_2022 a')
            ->join('com_event b','b.id=a.event_id','left')
            ->join('com_event_cate d','d.id=b.cate_id','left')
            ->join('com_integral_event_relation_users_2022 c','c.event_id = a.id','left')
            ->field('a.*,sum(c.integral_a) integral_a,sum(c.integral_b) integral_b,b.*,a.id id,d.name cate_name')
            ->group('a.id')
            ->where('a.prize_buckle_id',$id)->select();
        //参与人
        foreach ($event as $key=>$value){
            $users = M('com_integral_event_relation_users_2022 a')
                ->join('users b','b.id=a.user_id','left')
                ->where('a.event_id',$value['id'])
                ->field('a.*,b.name user_name')
                ->select();
            $event[$key]['user_list'] = $users;
        }
        //查询记录人奖励分数
//        $integral = M('com_config')->where('com_id',$this->com_id)->value('day_add_integral');
//        $this->assign('integral', $integral);
        $this->assign('theme', $theme);
        $this->assign('event', $event);
        return $this->fetch('event_info');
    }

    //个人明细查询
    public function reward_libaray(){
        $this->company_department_select();
        $where = ['l.com_id'=>$this->com_id];
        $where['u.role_id'] = ['neq',''];//去除总管理员
        $where['u.type'] = 1; //去除冻结人员
        input('name', '', 'trim') && $where['u.name'] = ['like', '%'.addslashes(input('name', '', 'trim')).'%'];
        input('department_id', 0, 'intval') && $where['u.department_id'] = input('department_id', 0, 'intval');
        if(input('date')){
            $date = input('date').'-01';
            $date1 = [ strtotime($date), strtotime('+1 month',strtotime($date))-1];
            $where['l.create_time'] = ['between',$date1];
        }else{
            $date = date('Y-m',time()).'-01';
            $date1 = [ strtotime($date), strtotime('+1 month',strtotime($date))-1];
            $where['l.create_time'] = ['between',$date1];
        }
        //列表导出
        if(input('export') == 1){
            set_time_limit(0);
            $list = db('com_integral_log')->alias('l')
                ->join('users u', 'u.id = l.user_id')
                ->where($where)
                ->group('l.year_month, l.user_id')
                ->order('l.year_month desc')
                ->field('l.*,
            l.type as l_type,
            u.job_number,
            u.name,
            SUM(if(l.type=1,l.integral_b,0)) as integral_b_sum_fixed,
            SUM(if(l.type=2,l.integral_b,0)) as integral_b_sum_prize,
            SUM(if(l.type=3,l.integral_b,0)) as integral_b_sum_qt,
            SUM(l.integral_a) as integral_a_sum
            ')
                ->select();
            foreach ($list as &$v) {
                $start_time = $v['year_month'];
                $end_time = strtotime('+1 month',$start_time)-1;
                $user_id = $v['user_id'];
                $v['integral_b_sum_total'] = SendIntegralNew::statistic_integral($start_time,$end_time,$user_id,$type=0);
                $v['total'] = SendIntegralNew::statistic_integral(strtotime('2019-01-01'),time(),$user_id,$type=1);
            }
            $this->reward_libaray_explode($list);
        }

        $list = db('com_integral_log')->alias('l')
            ->join('users u', 'u.id = l.user_id','right')
            ->where($where)
            ->group('l.year_month, l.user_id')
            ->order('l.year_month desc')
            ->field('l.*,
            l.type as l_type,
            u.job_number,
            u.name,
            SUM(if(l.type=1,l.integral_b,0)) as integral_b_sum_fixed,
            SUM(if(l.type=2,l.integral_b,0)) as integral_b_sum_prize,
            SUM(if(l.type=3,l.integral_b,0)) as integral_b_sum_qt,
            SUM(l.integral_a) as integral_a_sum
            ')
            ->paginate('', false, page_param());
        $list2 = $list->items();
        foreach ($list2 as &$v) {
            $start_time = $v['year_month'];
            $end_time = strtotime('+1 month',$start_time)-1;
            $user_id = $v['user_id'];
            $v['integral_b_sum_total'] = SendIntegralNew::statistic_integral($start_time,$end_time,$user_id,$type=0);
            $v['integral_a_sum_total'] = SendIntegralNew::statistic_integral_a($start_time,$end_time,$user_id,$type=0);
            $v['total'] = SendIntegralNew::statistic_integral(strtotime('2019-01-01'),time(),$user_id,$type=1);
        }
        $this->assign(compact('list', 'list2'));
        return $this->fetch();
    }
    //个人明细列表导出
    public function reward_libaray_explode_1($list){
        require EXTEND_PATH.'Export.php';
        $key = ['工号', '姓名', '月份', '固定积分', '奖扣任务', '考勤得分', '当月得分', 'A分总分', '累计得分'];
        $val = [];
        foreach ($list as $k => $v) {
            $val[] = [
                $v['job_number'],
                $v['name'],
                date('Ym', $v['year_month']),
                $v['integral_b_sum_fixed'],
                $v['integral_b_sum_prize'],
                $v['integral_b_sum_qt'],
                $v['integral_b_sum_total'],
                $v['integral_a_sum'],
                $v['total']
            ];
        }
        new \Export($key, $val, '个人明细查询');
        die;
    }
    //个人明细列表导出@stone
    public function reward_libaray_explode($list){
        $key = ['工号', '姓名', '月份', '固定积分', '奖扣任务', '考勤得分', '当月得分', 'A分总分', '累计得分'];
        $val = [];
        foreach ($list as $k => $v) {
            $val[] = [
                $v['job_number'],
                $v['name'],
                date('Ym', $v['year_month']),
                $v['integral_b_sum_fixed'],
                $v['integral_b_sum_prize'],
                $v['integral_b_sum_qt'],
                $v['integral_b_sum_total'],
                $v['integral_a_sum'],
                $v['total']
            ];
        }
        $name = '个人明细';
        //导出excel
        Export::excel($key,$val,$name,20,['A','C']);
    }

    //个人明细详情 author:zj
    public function reward_libaray_item(){
        $type = input('type','rc');
        $time = input('y_m','');
        $user_id = I('user_id',$this->user_id);
        $method = 'reward_libaray_'.$type;
        $list = $this->$method($time,$user_id);

        $this->assign('list', $list);
        $this->assign('username', session("user_com")['name']);
        $this->assign('job_number',session("user_com")['job_number']);
        $this->assign('y_m',$time);
        $this->assign('user_id',$user_id);

        return $this->fetch();
    }

    //个人明细详情导出 author:zj
    public function reward_libaray_item_explode()
    {
        $type = input('type','rc');
        $user_id = I('user_id',$this->user_id);
        $time = input('y_m','');
        $method = 'reward_libaray_'.$type;
        $data = $this->$method($time,$user_id,1);
        $method_explode = 'reward_libaray_item_'.$type;
        $this->$method_explode($data,$time);
    }

    //个人明细详情导出，日常奖扣 author:zj
    private function reward_libaray_item_rc($data, $time='')
    {
        require EXTEND_PATH.'Export.php';
        $keys = ['奖扣时间','主题','事件','A分','B分','初审人 / 终审人 / 记录人','审核状态'];
        $vals = [];
        $arr = [
            0=>'待初审',
            1=>'待终审',
            2=>'审核通过',
            3=>'作废',
            4=>'拟稿',
        ];
        foreach ($data as $v) {
            $vals[] = [
                date('Y-m-d',$v['prize_buckle_time']),
                $v['theme'],
                $v['e_name'],
                $v['integral_a'],
                $v['integral_b'],
                $v['first_check_user_name'].'/'.$v['last_check_user_name'].'/'.$v['record_user_name'],
                $arr[$v['status']]
            ];
        }
        //导出excel
        Export::excel($keys,$vals,'日常奖扣明细',20,['A','C']);
    }

    //个人明细详情导出，奖扣任务 author:zj
    private function reward_libaray_item_jk($data, $time='')
    {
        require EXTEND_PATH.'Export.php';
        $keys = ['任务名称','月份','任务指标','任务类型','未完成扣分类型','实际得分'];
        $Ym = date('Ym',$time);
        $vals = [
            [$data['prize_buckle_task_name'], $Ym, $data['prize_integral_target'].'/'.($data['prize_buckle_type'] == 1 ? '月' : '周'),'奖分任务','差额扣分',$data['prize_integral_del']],
            [$data['prize_buckle_task_name'], $Ym, $data['buckle_integral_target'].'/'.($data['prize_buckle_type'] == 1 ? '月' : '周'),'扣分任务','差额扣分',$data['buckle_integral_del']],
            [$data['prize_buckle_task_name'], $Ym, $data['people_target'].'/'.($data['people_type'] == 1 ? '日' : $data['people_type'] == 2 ? '周' : '月'),'奖扣人次任务','未完成人次任务扣分:'.$data['people_del'],$data['people_del_total']],
            [$data['prize_buckle_task_name'], $Ym, $data['rate_target'].'%/月','奖扣比例任务','差额扣分',$data['rate_del']],
        ];
        Export::excel($keys,$vals,'奖扣任务明细',20,['A','C']);
    }

    //个人明细详情导出，固定积分 author:zj
    private function reward_libaray_item_gd($data, $time='')
    {
        require EXTEND_PATH.'Export.php';
        $keys = ['固定积分名称','月份','固定积分','实际得分'];
        $Ym = date('Ym',$time);
        foreach ($data as $v) {
            $vals[] = [
                $v['name'],
                date('Y-m',$time),
                $v['integral_b_sum'],
                $time == strtotime(date('Y-m',time())) ? 0 :  $v['integral_b_sum']
            ];
        }
        Export::excel($keys,$vals,'固定积分明细',20,['A','C']);

    }

    //个人明细详情导出，其他积分 author:zj
    private function reward_libaray_item_qt($data, $time='')
    {
//        时间	类型	分值
        require EXTEND_PATH.'Export.php';
        $keys = ['时间','类型','分值'];
        $Ym = date('Ym',$time);
        $arr = [
            1=>'事假',
            2=>'病假',
            3=>'其他',
        ];
        $vals = [];
        foreach ($data as $v) {
            $vals[] = [
                date('Ym',$v['create_time']),
                $arr[$v['leave_type']]??'全勤',
                $v['integral_b'],
            ];
        }
        Export::excel($keys,$vals,'其他积分明细',20,['A','C']);
    }

    //个人明细 日常奖扣 author:zj
    private function reward_libaray_rc($time,$user_id,$explode=0){
//        $where['']
        if($explode == 1){
            $list = db('com_integral_event_relation_users')->alias('l')
//            ->join('users u', 'u.id = l.user_id')
                ->join('com_integral_prize_buckle_relation_event e', 'l.event_id = e.id', 'left')
                ->join('com_event ce', 'e.event_id = ce.id', 'left')
                ->join('com_integral_prize_buckle b', 'e.prize_buckle_id = b.id', 'left')
                ->join('users u', 'b.first_check_user_id = u.id', 'left')
                ->join('users u2', 'b.last_check_user_id = u2.id', 'left')
                ->join('users u3', 'b.record_user_id = u3.id', 'left')
                ->where('l.is_cancellation', '0')
                ->where('b.prize_buckle_time','between', [strtotime(date('Y-m',$time)),strtotime('+1 month',strtotime(date('Y-m',$time)))-1])
                ->where('l.user_id', $user_id)
                ->group('l.id')
                ->field('l.*,
            COALESCE(SUM(IF(l.piece_rate=0,l.integral_b,l.piece_rate*l.integral_b)),0) integral_b,
            COALESCE(SUM(IF(l.piece_rate=0,l.integral_a,l.piece_rate*l.integral_a)),0) integral_a,
            u.name as first_check_user_name, u2.name as last_check_user_name, u3.name as record_user_name, b.prize_buckle_time, b.theme, b.status, ce.name e_name')
                ->order('b.prize_buckle_time desc,l.id desc')
                ->select();
        }else {
            $list = db('com_integral_event_relation_users')->alias('l')
//            ->join('users u', 'u.id = l.user_id')
                ->join('com_integral_prize_buckle_relation_event e', 'l.event_id = e.id', 'left')
                ->join('com_event ce', 'e.event_id = ce.id', 'left')
                ->join('com_integral_prize_buckle b', 'e.prize_buckle_id = b.id', 'left')
                ->join('users u', 'b.first_check_user_id = u.id', 'left')
                ->join('users u2', 'b.last_check_user_id = u2.id', 'left')
                ->join('users u3', 'b.record_user_id = u3.id', 'left')
                ->where('l.is_cancellation', '0')
                ->where('b.prize_buckle_time', 'between', [strtotime(date('Y-m', $time)), strtotime('+1 month', strtotime(date('Y-m', $time))) - 1])
                ->where('l.user_id', $user_id)
                ->group('l.id')
                ->field('l.*,
            COALESCE(SUM(IF(l.piece_rate=0,l.integral_b,l.piece_rate*l.integral_b)),0) integral_b,
            COALESCE(SUM(IF(l.piece_rate=0,l.integral_a,l.piece_rate*l.integral_a)),0) integral_a,
            u.name as first_check_user_name, u2.name as last_check_user_name, u3.name as record_user_name, b.prize_buckle_time, b.theme, b.status, ce.name e_name')
                ->order('b.prize_buckle_time desc,l.id desc')
                ->paginate('', false, page_param());
        }
        return $list;
//        $return = [
//            'list'=>$list
//        ];
//        $this->assign($return);
//        return $this->fetch();
    }

    //个人明细 奖扣任务 author:zj
    private function reward_libaray_jk($time,$user_id){
        $time = date('Y-m',$time);
        $start = strtotime($time.'-01');
        $end = strtotime('+1 month -1 day',$start);
        //查询用户配置
        $sys = M('com_prize_buckle_config_relation_users a')
            ->join('com_prize_buckle_config b','a.prize_buckle_id=b.id','left')
            ->where('a.user_id', $user_id)
            ->field('b.*')
            ->find();
        $list = [];
        //判断是否是本月
        if(date('Y-m',time()) == $time) {
            $list = \app\api\logic\Task::get_prize_buckle_task($user_id,$time);
            $list['prize_buckle_task_name'] = $sys['name'];
            $list['man_deduct'] = $sys['man_deduct'];
        }else{
            $where_a = [];
            $where_a['user_id'] = $user_id;
            $where_a['year_month'] = strtotime($time);
            $res = M('com_prize_buckle_task_log')->where($where_a)->find();
//            dump($res);die;
            $num = (int)date('d',$end);
            //判断是否有记录
            if($res){//有记录
                $list = [
                    'prize_integral_target'=>$res['prize_integral_target'],//奖分目标
                    'buckle_integral_target'=>$res['buckle_integral_target'],//扣分目标
                    'prize_integral_com'=>$res['total_prize_integral'],//奖分完成值
                    'buckle_integral_com'=>$res['total_buckle_integral'],//扣分完成值
                    'prize_integral_status'=>$res['prize_status'],//奖分状态  0未完成  1已完成
                    'buckle_integral_status'=>$res['buckle_status'],//扣分状态  0未完成 1已完成
                    'prize_integral_del'=>$res['prize_integral_del'],//奖分未完成扣分
                    'buckle_integral_del'=>$res['buckle_integral_del'],//奖分未完成扣分
                    'rate_target'=>$res['rate_target'],//奖扣比例目标
                    'rate_com'=>$res['total_rate'],//奖扣比例已完成值
                    'rate_status'=>$res['rate_status'],//完成状态 0未完成 1已完成
                    'rate_del'=>$res['rate_del'],//比例未完成扣分
                    'people_day'=>$num,//人次月天数
                    'people_type'=>$res['people_type'],//人次类型
                    'people_day_total'=>$num,//人次统计天数
                    'people_day_not'=>$num,//人次未完成天数
                    'people_target'=>$res['people_target']??0,//奖扣人次目标
                    'people_com'=>0,//奖扣人次已完成值
                    'people_del'=>$res['people_target_del'],//人次未完成扣分
                    'people_del_total'=>$res['people_del'],//人次未完成总扣分
                    'people_status'=>$res['people_status'],//人次状态  0未完成 1已完成
                    'prize_buckle_type'=>$res['prize_integral_type'],//奖扣任务类型 0周任务  1月任务
                    'total_people'=>$res['total_people'],//总人次
                    'total_del_integral'=>$res['total_del_integral'],//总扣分
                    'people_target_del' =>$res['people_target_del'], //人次未完成单次扣分
                    'prize_buckle_task_name' =>$res['prize_buckle_task_name'], //人次未完成单次扣分
                    'man_deduct' =>$res['people_target_del']//人次未完成单次扣分
                ];
            }else{
                $list = [
                    'prize_integral_target'=>0,//奖分目标
                    'buckle_integral_target'=>0,//扣分目标
                    'prize_integral_com'=>0,//奖分完成值
                    'buckle_integral_com'=>0,//扣分完成值
                    'prize_integral_status'=>0,//奖分状态  0未完成  1已完成
                    'buckle_integral_status'=>0,//扣分状态  0未完成 1已完成
                    'prize_integral_del'=>0,//奖分未完成扣分
                    'buckle_integral_del'=>0,//奖分未完成扣分
                    'rate_target'=>0,//奖扣比例目标
                    'rate_com'=>0,//奖扣比例已完成值
                    'rate_status'=>0,//完成状态 0未完成 1已完成
                    'rate_del'=>0,//比例未完成扣分
                    'people_day'=>$num,//人次月天数
                    'people_type'=>0,//人次类型
                    'people_day_total'=>$num,//人次统计天数
                    'people_day_not'=>$num,//人次未完成天数
                    'people_target'=>0,//奖扣人次目标
                    'people_com'=>0,//奖扣人次已完成值
                    'people_del'=>0,//人次未完成扣分
                    'people_del_total'=>0,//人次未完成总扣分
                    'people_status'=>0,//人次状态  0未完成 1已完成
                    'prize_buckle_type'=>0,//奖扣任务类型 0周任务  1月任务
                    'total_people'=>0,//总人次
                    'total_del_integral'=>0,//总扣分
                    'people_target_del' =>0, //人次未完成单次扣分
                    'prize_buckle_task_name' =>0, //人次未完成单次扣分
                    'man_deduct' =>0//人次未完成单次扣分
                ];
            }
        }
        return $list;
//        $this->assign('data',$data);
    }

    //个人明细 固定积分 author:zj
    private function reward_libaray_gd($time,$user_id){
        //com_integral_log
        //com_fixed_relation_users
        //com_fixed_integral
//        $list = [];
//        if(date('Y-m',time()) == $time) {
//            $list = M('com_fixed_relation_users cfru')
//                ->join('com_fixed_integral cfi', 'cfi.id = cfru.fixed_id')
//                ->where(['cfru.user_id' => $user_id, 'cil.com_id' => $this->com_id])
//                ->field('cfi.name, SUM(cil.integral_b) as integral_b_sum')
//                ->group('cfru.fixed_id')
//                ->paginate();
//        }else {
            $list = M('com_integral_log cil')
                ->join('com_fixed_relation_users cfru', 'cfru.user_id = cil.user_id','left')
                ->join('com_fixed_integral cfi', 'cfi.id = cfru.fixed_id','left')
                ->where(['cil.user_id' => $user_id, 'cil.com_id' => $this->com_id, 'cil.type' => 1, 'cil.year_month' => $time])
                ->field('cfi.name, SUM(cil.integral_b) as integral_b_sum,cfi.integral as integral_b')
                ->order('cil.create_time desc')
                ->group('cil.user_id')
                ->paginate('', false, page_param());
//        }

        return $list;
//        $this->assign('list', $list);
    }

    //个人明细 其他积分 author:zj
    private function reward_libaray_qt($time,$user_id){
        $list = M('com_integral_log')
            ->where(['user_id' => $user_id, 'com_id' => $this->com_id, 'leave_type'=>['>', 0],'year_month' => $time])
            ->order('create_time desc')
            ->paginate('', false, page_param());
        return $list;
//        $this->assign('list', $list);
    }

    /**
     * 日常奖扣查询，author:zj
     * @param int $by           //排序调用，
     * @param array $params     //导出条件
     * @return mixed
     */
    public function daily($by = 0)
    {
        //部门、组织机构
        $this->company_department_select();
        //事件
        $eventList = $this->event_daily_search();

        $assigns = [
            'json_eventList'=>json_encode($eventList),      //弹框，事件
            'eventList'=>$eventList,                        //下拉框，事件
            'event_type_tree'=>event_type_tree($eventList)  //事件类型
        ];

        $this->assign($assigns);

        $where = $this->daily_search(input());
        $where['u.com_id'] = $this->com_id;
        $where['u1.type'] = 1; //未冻结用户
        $where['u.is_cancellation'] = 0;//未作废
        $field = [
            'u1.name as user_name',                     //奖扣对象姓名
            'u1.base_integral as base_integral',                     //基础分
            'u1.working_age_integral as working_age_integral',                     //工龄分
            'u1.job_number as job_number',              //奖扣对象工号
            'b.prize_buckle_time as prize_buckle_time', //奖扣时间
            'b.create_time as create_time',           //记录时间
            'b.theme as theme',                       //主题
            'ce.name as name',                       //事件
            'if(u.piece_rate>0,u.integral_a*u.piece_rate,u.integral_a) as integral_a',
            'if(u.piece_rate>0,u.integral_b*u.piece_rate,u.integral_b) as integral_b',             //B分
            'u2.job_number as rjob_number',                   //记录人工号
            'u2.name as record_name',                   //记录人
            'u3.job_number as fjob_number',                    //初审人工号
            'u3.name as first_name',                    //初审人
            'u4.job_number as ljob_number',                     //终审人工号
            'u4.name as last_name',                     //终审人
            'b.status as status',                     //审核状态
            'e.event_desc as event_desc',             //事件描述
            'b.id as id',             //事件描述
            'u.user_id'
        ];
//        var_dump($where);die;
        $query =  $by == 0 ? 'paginate' : 'select';
//        var_dump($where);die;
        $list = M('com_integral_event_relation_users u')
            ->join('com_integral_prize_buckle_relation_event e', 'e.id = u.event_id', 'left')
            ->join('com_integral_prize_buckle b', 'b.id = e.prize_buckle_id', 'left')
            ->join('com_event ce', 'ce.id = e.event_id', 'left')
            //获取用户名称
            ->join('users u1', 'u1.id = u.user_id', 'left')
            ->join('users u2', 'u2.id = b.record_user_id', 'left')
            ->join('users u3', 'u3.id = b.first_check_user_id', 'left')
            ->join('users u4', 'u4.id = b.last_check_user_id', 'left')
            ->where($where)
            ->field($field)
            ->order('b.create_time desc,b.prize_buckle_time desc')
            ->group('b.id, e.id, u.user_id')
            ->$query();
//        var_dump($_SERVER);die;

        if($by == 1) {
            return $list;
        }else{
            $url = str_replace('page=','',$_SERVER['REQUEST_URI']);
            $page_list = str_replace('/company/integral/daily?',$url.'&',$list->render());
            $this->assign('page_list',$page_list);
            //显示
            $event_ids = input();
            $event_ids = $event_ids['event_ids']??'';
            if($event_ids){
                $this->assign('event_info_num', '已选择'.count($event_ids).'个事件');

                $event_info = db('com_event a')
                    ->join('com_event_cate b', 'a.cate_id = b.id', 'LEFT')
                    ->join('com_event_cate c', 'b.pid = c.id', 'LEFT')
                    ->join('com_event_cate d', 'c.pid = d.id', 'LEFT')
                    ->where('a.id', 'in', $event_ids)
                    ->field('a.*,b.name cate_name,c.name p_cate_name, d.name pp_cate_name')

                    ->select();
                if($event_info){
                    foreach ($event_info as &$v) {
                        $v['show_cate_name'] = trim($v['pp_cate_name'].$v['p_cate_name'].'/'.$v['cate_name'], '/');
                    }
                    $this->assign(compact('event_info'));
                }
            }
            $this->assign(compact('list'));
            return $this->fetch();
        }
    }
    /**
     * 日常奖扣查询，author:zj
     * @param int $by           //排序调用，
     * @param array $params     //导出条件
     * @return mixed
     */
    public function daily_2021($by = 0)
    {
        //部门、组织机构
        $this->company_department_select();
        //事件
        $eventList = $this->event_daily_search();

        $assigns = [
            'json_eventList'=>json_encode($eventList),      //弹框，事件
            'eventList'=>$eventList,                        //下拉框，事件
            'event_type_tree'=>event_type_tree($eventList)  //事件类型
        ];

        $this->assign($assigns);

        $where = $this->daily_search(input());
        $where['u.com_id'] = $this->com_id;
        $where['u1.type'] = 1; //未冻结用户
        $where['u.is_cancellation'] = 0;//未作废
        $field = [
            'u1.name as user_name',                     //奖扣对象姓名
            'u1.base_integral as base_integral',                     //基础分
            'u1.working_age_integral as working_age_integral',                     //工龄分
            'u1.job_number as job_number',              //奖扣对象工号
            'b.prize_buckle_time as prize_buckle_time', //奖扣时间
            'b.create_time as create_time',           //记录时间
            'b.theme as theme',                       //主题
            'ce.name as name',                       //事件
            'if(u.piece_rate>0,u.integral_a*u.piece_rate,u.integral_a) as integral_a',
            'if(u.piece_rate>0,u.integral_b*u.piece_rate,u.integral_b) as integral_b',             //B分
            'u2.job_number as rjob_number',                   //记录人工号
            'u2.name as record_name',                   //记录人
            'u3.job_number as fjob_number',                    //初审人工号
            'u3.name as first_name',                    //初审人
            'u4.job_number as ljob_number',                     //终审人工号
            'u4.name as last_name',                     //终审人
            'b.status as status',                     //审核状态
            'e.event_desc as event_desc',             //事件描述
            'b.id as id',             //事件描述
            'u.user_id'
        ];
//        var_dump($where);die;
        $query =  $by == 0 ? 'paginate' : 'select';
//        var_dump($where);die;
        $list = M('com_integral_event_relation_users_2021 u')
            ->join('com_integral_prize_buckle_relation_event_2021 e', 'e.id = u.event_id', 'left')
            ->join('com_integral_prize_buckle_2021 b', 'b.id = e.prize_buckle_id', 'left')
            ->join('com_event ce', 'ce.id = e.event_id', 'left')
            //获取用户名称
            ->join('users u1', 'u1.id = u.user_id', 'left')
            ->join('users u2', 'u2.id = b.record_user_id', 'left')
            ->join('users u3', 'u3.id = b.first_check_user_id', 'left')
            ->join('users u4', 'u4.id = b.last_check_user_id', 'left')
            ->where($where)
            ->field($field)
            ->order('b.create_time desc,b.prize_buckle_time desc')
            ->group('b.id, e.id, u.user_id')
            ->$query();
//        var_dump($_SERVER);die;

        if($by == 1) {
            return $list;
        }else{
            $url = str_replace('page=','',$_SERVER['REQUEST_URI']);
            $page_list = str_replace('/company/integral/daily_2021?',$url.'&',$list->render());
            $this->assign('page_list',$page_list);
            //显示
            $event_ids = input();
            $event_ids = $event_ids['event_ids']??'';
            if($event_ids){
                $this->assign('event_info_num', '已选择'.count($event_ids).'个事件');

                $event_info = db('com_event a')
                    ->join('com_event_cate b', 'a.cate_id = b.id', 'LEFT')
                    ->join('com_event_cate c', 'b.pid = c.id', 'LEFT')
                    ->join('com_event_cate d', 'c.pid = d.id', 'LEFT')
                    ->where('a.id', 'in', $event_ids)
                    ->field('a.*,b.name cate_name,c.name p_cate_name, d.name pp_cate_name')

                    ->select();
                if($event_info){
                    foreach ($event_info as &$v) {
                        $v['show_cate_name'] = trim($v['pp_cate_name'].$v['p_cate_name'].'/'.$v['cate_name'], '/');
                    }
                    $this->assign(compact('event_info'));
                }
            }
            $this->assign(compact('list'));
            return $this->fetch();
        }
    }
    public function daily_2022($by = 0)
    {
        //部门、组织机构
        $this->company_department_select();
        //事件
        $eventList = $this->event_daily_search();

        $assigns = [
            'json_eventList'=>json_encode($eventList),      //弹框，事件
            'eventList'=>$eventList,                        //下拉框，事件
            'event_type_tree'=>event_type_tree($eventList)  //事件类型
        ];

        $this->assign($assigns);

        $where = $this->daily_search(input());
        $where['u.com_id'] = $this->com_id;
        $where['u1.type'] = 1; //未冻结用户
        $where['u.is_cancellation'] = 0;//未作废
        $field = [
            'u1.name as user_name',                     //奖扣对象姓名
            'u1.base_integral as base_integral',                     //基础分
            'u1.working_age_integral as working_age_integral',                     //工龄分
            'u1.job_number as job_number',              //奖扣对象工号
            'b.prize_buckle_time as prize_buckle_time', //奖扣时间
            'b.create_time as create_time',           //记录时间
            'b.theme as theme',                       //主题
            'ce.name as name',                       //事件
            'if(u.piece_rate>0,u.integral_a*u.piece_rate,u.integral_a) as integral_a',
            'if(u.piece_rate>0,u.integral_b*u.piece_rate,u.integral_b) as integral_b',             //B分
            'u2.job_number as rjob_number',                   //记录人工号
            'u2.name as record_name',                   //记录人
            'u3.job_number as fjob_number',                    //初审人工号
            'u3.name as first_name',                    //初审人
            'u4.job_number as ljob_number',                     //终审人工号
            'u4.name as last_name',                     //终审人
            'b.status as status',                     //审核状态
            'e.event_desc as event_desc',             //事件描述
            'b.id as id',             //事件描述
            'u.user_id'
        ];
//        var_dump($where);die;
        $query =  $by == 0 ? 'paginate' : 'select';
//        var_dump($where);die;
        $list = M('com_integral_event_relation_users_2022 u')
            ->join('com_integral_prize_buckle_relation_event_2022 e', 'e.id = u.event_id', 'left')
            ->join('com_integral_prize_buckle_2022 b', 'b.id = e.prize_buckle_id', 'left')
            ->join('com_event ce', 'ce.id = e.event_id', 'left')
            //获取用户名称
            ->join('users u1', 'u1.id = u.user_id', 'left')
            ->join('users u2', 'u2.id = b.record_user_id', 'left')
            ->join('users u3', 'u3.id = b.first_check_user_id', 'left')
            ->join('users u4', 'u4.id = b.last_check_user_id', 'left')
            ->where($where)
            ->field($field)
            ->order('b.create_time desc,b.prize_buckle_time desc')
            ->group('b.id, e.id, u.user_id')
            ->$query();
//        var_dump($_SERVER);die;

        if($by == 1) {
            return $list;
        }else{
            $url = str_replace('page=','',$_SERVER['REQUEST_URI']);
            $page_list = str_replace('/company/integral/daily_2022?',$url.'&',$list->render());
            $this->assign('page_list',$page_list);
            //显示
            $event_ids = input();
            $event_ids = $event_ids['event_ids']??'';
            if($event_ids){
                $this->assign('event_info_num', '已选择'.count($event_ids).'个事件');

                $event_info = db('com_event a')
                    ->join('com_event_cate b', 'a.cate_id = b.id', 'LEFT')
                    ->join('com_event_cate c', 'b.pid = c.id', 'LEFT')
                    ->join('com_event_cate d', 'c.pid = d.id', 'LEFT')
                    ->where('a.id', 'in', $event_ids)
                    ->field('a.*,b.name cate_name,c.name p_cate_name, d.name pp_cate_name')

                    ->select();
                if($event_info){
                    foreach ($event_info as &$v) {
                        $v['show_cate_name'] = trim($v['pp_cate_name'].$v['p_cate_name'].'/'.$v['cate_name'], '/');
                    }
                    $this->assign(compact('event_info'));
                }
            }
            $this->assign(compact('list'));
            return $this->fetch();
        }
    }

    //日常奖扣导出 author:zj
    public function daily_export()
    {
        require EXTEND_PATH.'Export.php';
        $keys = ['奖扣对象','工号','奖扣时间','记录时间','主题','事件名称','A分','B分','初审人工号','初审人','终审人工号','终审人','记录人','审核状态','事件描述'];
        $data = $this->daily(1);
        $statusArr = [
            0=>'待初审',
            1=>'待终审',
            2=>'审核通过',
            3=>'作废',
            4=>'拟稿',
        ];
        $vals = [];
        foreach ($data as $key=>$v) {
            $vals[] = [
                $v['user_name'],
                $v['job_number'],
                date('Y-m-d',$v['prize_buckle_time']),
                date('Y-m-d H:i',$v['create_time']),
                $v['theme'],
                $v['name'],
                $v['integral_a'],
                $v['integral_b'],
                $v['fjob_number'],
                $v['first_name'],
                $v['ljob_number'],
                $v['last_name'],
                $v['record_name'],
                $statusArr[$v['status']]??'',
                $v['event_desc']??'--',
            ];
        }
        $name = '日常奖扣';
        //导出excel
        Export::excel($keys,$vals,$name,20,['C']);
    }
    //日常奖扣导出 author:zj
    public function daily_2021_export()
    {
        require EXTEND_PATH.'Export.php';
        $keys = ['奖扣对象','工号','奖扣时间','记录时间','主题','事件名称','A分','B分','初审人工号','初审人','终审人工号','终审人','记录人','审核状态','事件描述'];
        $data = $this->daily_2021(1);
        $statusArr = [
            0=>'待初审',
            1=>'待终审',
            2=>'审核通过',
            3=>'作废',
            4=>'拟稿',
        ];
        $vals = [];
        foreach ($data as $key=>$v) {
            $vals[] = [
                $v['user_name'],
                $v['job_number'],
                date('Y-m-d',$v['prize_buckle_time']),
                date('Y-m-d H:i',$v['create_time']),
                $v['theme'],
                $v['name'],
                $v['integral_a'],
                $v['integral_b'],
                $v['fjob_number'],
                $v['first_name'],
                $v['ljob_number'],
                $v['last_name'],
                $v['record_name'],
                $statusArr[$v['status']]??'',
                $v['event_desc']??'--',
            ];
        }
        $name = '日常奖扣';
        //导出excel
        Export::excel($keys,$vals,$name,20,['C']);
    }
    //日常奖扣导出 author:zj
    public function daily_2022_export()
    {
        require EXTEND_PATH.'Export.php';
        $keys = ['奖扣对象','工号','奖扣时间','记录时间','主题','事件名称','A分','B分','初审人工号','初审人','终审人工号','终审人','记录人','审核状态','事件描述'];
        $data = $this->daily_2022(1);
        $statusArr = [
            0=>'待初审',
            1=>'待终审',
            2=>'审核通过',
            3=>'作废',
            4=>'拟稿',
        ];
        $vals = [];
        foreach ($data as $key=>$v) {
            $vals[] = [
                $v['user_name'],
                $v['job_number'],
                date('Y-m-d',$v['prize_buckle_time']),
                date('Y-m-d H:i',$v['create_time']),
                $v['theme'],
                $v['name'],
                $v['integral_a'],
                $v['integral_b'],
                $v['fjob_number'],
                $v['first_name'],
                $v['ljob_number'],
                $v['last_name'],
                $v['record_name'],
                $statusArr[$v['status']]??'',
                $v['event_desc']??'--',
            ];
        }
        $name = '日常奖扣';
        //导出excel
        Export::excel($keys,$vals,$name,20,['C']);
    }

    //日常奖扣查询->当前条件排名，author:zj
    public function by_condition($export = false)
    {
        $base_integral = I('base_integral',0);
        $working_age_integral = I('working_age_integral',0);
        $res = $this->daily(1);
//        var_dump($res);die;
        $returnData = [];

        if(!$res){
            if($export){
                return $returnData;
            }
            $this->assign('list', $returnData);
            return $this->fetch();
        }
//         var_dump($returnData);die;
        foreach ($res as $v) {
            if(!isset($returnData[$v['user_id']])){
                $returnData[$v['user_id']]['user_name'] = $v['user_name'];
                $returnData[$v['user_id']]['user_id'] = $v['user_id'];
                $returnData[$v['user_id']]['job_number'] = $v['job_number'];
                $returnData[$v['user_id']]['integral_positive'] = 0;
                $returnData[$v['user_id']]['integral_negative'] = 0;
                $returnData[$v['user_id']]['integral_total'] = 0;
            }
            $returnData[$v['user_id']]['base_integral'] = $v['base_integral'];
            $returnData[$v['user_id']]['working_age_integral'] = $v['working_age_integral'];
            $positive = $v['integral_b'] >= 0 ? $v['integral_b'] : 0;
            $negative = $v['integral_b'] < 0 ? $v['integral_b'] : 0;
            $returnData[$v['user_id']]['integral_positive'] += $positive;
            $returnData[$v['user_id']]['integral_negative'] += $negative;
            $returnData[$v['user_id']]['integral_total'] += $v['integral_b'];
        }
        foreach ($returnData as $key=>$value){
            if($base_integral == 0){
                $returnData[$key]['integral_total'] += $v['base_integral'];
            }
            if($working_age_integral == 0){
                $returnData[$key]['integral_total'] += $v['working_age_integral'];
            }
        }

        //二维数组，以integral_total字段倒序
        $integral_total = array_column($returnData,'integral_total');
        array_multisort($integral_total,SORT_DESC,$returnData);

        if($export){
            return $returnData;
        }
        $this->assign('list', $returnData);
        return $this->fetch();
    }
    //日常奖扣查询->当前条件排名，导出。@stone
    public function by_condition_export()
    {
        $keys = ['排名','姓名','工号','所有奖分','所有扣分','所有得分'];
        $data = $this->by_condition(true);
        $vals = [];
        foreach ($data as $key=>$v) {
            $vals[] = [
                $key+1,
                $v['user_name'],
                $v['job_number'],
                $v['integral_positive'],
                $v['integral_negative'],
                $v['integral_total'],
            ];
        }
        $name = '日常奖扣-条件排名';
        //导出excel
        Export::excel($keys,$vals,$name,20,['C']);
    }
    //日常奖扣查询->当前条件排名，author:zj
    public function by_condition_2021($export = false)
    {
        $base_integral = I('base_integral',0);
        $working_age_integral = I('working_age_integral',0);
        $res = $this->daily_2021(1);
//        var_dump($res);die;
        $returnData = [];

        if(!$res){
            if($export){
                return $returnData;
            }
            $this->assign('list', $returnData);
            return $this->fetch();
        }
//         var_dump($returnData);die;
        foreach ($res as $v) {
            if(!isset($returnData[$v['user_id']])){
                $returnData[$v['user_id']]['user_name'] = $v['user_name'];
                $returnData[$v['user_id']]['user_id'] = $v['user_id'];
                $returnData[$v['user_id']]['job_number'] = $v['job_number'];
                $returnData[$v['user_id']]['integral_positive'] = 0;
                $returnData[$v['user_id']]['integral_negative'] = 0;
                $returnData[$v['user_id']]['integral_total'] = 0;
            }
            $returnData[$v['user_id']]['base_integral'] = $v['base_integral'];
            $returnData[$v['user_id']]['working_age_integral'] = $v['working_age_integral'];
            $positive = $v['integral_b'] >= 0 ? $v['integral_b'] : 0;
            $negative = $v['integral_b'] < 0 ? $v['integral_b'] : 0;
            $returnData[$v['user_id']]['integral_positive'] += $positive;
            $returnData[$v['user_id']]['integral_negative'] += $negative;
            $returnData[$v['user_id']]['integral_total'] += $v['integral_b'];
        }
        foreach ($returnData as $key=>$value){
            if($base_integral == 0){
                $returnData[$key]['integral_total'] += $v['base_integral'];
            }
            if($working_age_integral == 0){
                $returnData[$key]['integral_total'] += $v['working_age_integral'];
            }
        }

        //二维数组，以integral_total字段倒序
        $integral_total = array_column($returnData,'integral_total');
        array_multisort($integral_total,SORT_DESC,$returnData);

        if($export){
            return $returnData;
        }
        $this->assign('list', $returnData);
        return $this->fetch();
    }
    public function by_condition_2022($export = false)
    {
        $base_integral = I('base_integral',0);
        $working_age_integral = I('working_age_integral',0);
        $res = $this->daily_2022(1);
//        var_dump($res);die;
        $returnData = [];

        if(!$res){
            if($export){
                return $returnData;
            }
            $this->assign('list', $returnData);
            return $this->fetch();
        }
//         var_dump($returnData);die;
        foreach ($res as $v) {
            if(!isset($returnData[$v['user_id']])){
                $returnData[$v['user_id']]['user_name'] = $v['user_name'];
                $returnData[$v['user_id']]['user_id'] = $v['user_id'];
                $returnData[$v['user_id']]['job_number'] = $v['job_number'];
                $returnData[$v['user_id']]['integral_positive'] = 0;
                $returnData[$v['user_id']]['integral_negative'] = 0;
                $returnData[$v['user_id']]['integral_total'] = 0;
            }
            $returnData[$v['user_id']]['base_integral'] = $v['base_integral'];
            $returnData[$v['user_id']]['working_age_integral'] = $v['working_age_integral'];
            $positive = $v['integral_b'] >= 0 ? $v['integral_b'] : 0;
            $negative = $v['integral_b'] < 0 ? $v['integral_b'] : 0;
            $returnData[$v['user_id']]['integral_positive'] += $positive;
            $returnData[$v['user_id']]['integral_negative'] += $negative;
            $returnData[$v['user_id']]['integral_total'] += $v['integral_b'];
        }
        foreach ($returnData as $key=>$value){
            if($base_integral == 0){
                $returnData[$key]['integral_total'] += $v['base_integral'];
            }
            if($working_age_integral == 0){
                $returnData[$key]['integral_total'] += $v['working_age_integral'];
            }
        }

        //二维数组，以integral_total字段倒序
        $integral_total = array_column($returnData,'integral_total');
        array_multisort($integral_total,SORT_DESC,$returnData);

        if($export){
            return $returnData;
        }
        $this->assign('list', $returnData);
        return $this->fetch();
    }
    //日常奖扣查询->当前条件排名，导出。@stone
    public function by_condition_2021_export()
    {
        $keys = ['排名','姓名','工号','所有奖分','所有扣分','所有得分'];
        $data = $this->by_condition_2021(true);
        $vals = [];
        foreach ($data as $key=>$v) {
            $vals[] = [
                $key+1,
                $v['user_name'],
                $v['job_number'],
                $v['integral_positive'],
                $v['integral_negative'],
                $v['integral_total'],
            ];
        }
        $name = '日常奖扣-条件排名';
        //导出excel
        Export::excel($keys,$vals,$name,20,['C']);
    }
    public function by_condition_2022_export()
    {
        $keys = ['排名','姓名','工号','所有奖分','所有扣分','所有得分'];
        $data = $this->by_condition_2022(true);
        $vals = [];
        foreach ($data as $key=>$v) {
            $vals[] = [
                $key+1,
                $v['user_name'],
                $v['job_number'],
                $v['integral_positive'],
                $v['integral_negative'],
                $v['integral_total'],
            ];
        }
        $name = '日常奖扣-条件排名';
        //导出excel
        Export::excel($keys,$vals,$name,20,['C']);
    }

    //日常奖扣查询，搜索。author:zj
    private function daily_search($params)
    {
//        var_dump($params);die;
        $where = [];

        //部门、组织机构
//        $department_id = input('department_id', 0, 'intval');
        $department_id = $params['department_id']??'';
        if($department_id){
            $department_ids = department_child([$department_id], $this->com_id);
            $where['u1.department_id'] = ['in',$department_ids];
        }

        //事件、事件名称
//        $event_ids = input('event_ids', 0, 'intval');
        $event_ids = $params['event_ids']??'';
        if(is_array($event_ids) && count($event_ids) > 0){
            $where['ce.id'] = ['in', $event_ids];
        }elseif($event_ids){
            $where['ce.id'] = ['in', explode(',',$event_ids)];
        }

        //事件类型
//        $type_event_id = input('type_event_id');
        $type_event_id = $params['type_event_id']??'';
        if(!empty($type_event_id)){
            $tmpIds = [$type_event_id];
            $ids = db('com_event_cate')->where(['pid'=>['in', $tmpIds], 'com_id'=>$this->com_id])->column('id');
            $ids = array_merge($ids, $tmpIds);
            $where['ce.cate_id'] = ['in', $ids];
//            if(isset($where['ce.id'])){        //如果有事件、事件名称的查询条件，就需要在这里重写
//                $where['ce.id'] = [ ['in',$event_ids], ['in', $event_ids], 'or'];
//            }else{
//                $where['ce.id'] = ['in', $event_ids];
//            }
        }

        //初审人
//        $first_check_user_id = input('first_check_user_id');
        $first_check_user_id = $params['first_check_user_id']??'';
        if($first_check_user_id) $where['b.first_check_user_id'] = $first_check_user_id;
        //终审人
//        $last_check_user_id = input('last_check_user_id');
        $last_check_user_id = $params['last_check_user_id']??'';
        if($last_check_user_id) $where['b.last_check_user_id'] = $last_check_user_id;

        //记录人
//        $record_user_id = input('record_user_id');
        $record_user_id = $params['record_user_id']??'';
        if($record_user_id) $where['b.record_user_id'] = $record_user_id;

        //A分区间
//        $a_start = input('integral_a_start/d','');
//        $a_end = input('integral_a_end/d','');
        $a_start = $params['integral_a_start']??'';
        $a_end = $params['integral_a_end']??'';
        if($a_start && $a_end) $where['u.integral_a'] = ['between',[$a_start,$a_end]];
        //B分区间
//        $b_start = input('integral_b_start/d','');
//        $b_end = input('integral_b_end/d','');
        $b_start = $params['integral_b_start']??'';
        $b_end = $params['integral_b_end']??'';
        if($b_start && $b_end) $where['u.integral_b'] = ['between',[$b_start,$b_end]];
        //主题
//        $themeName = input('theme_name','');
        $themeName = $params['theme_name']??'';
        if($themeName){
            $where['b.theme|ce.name'] = ['like','%'.$themeName.'%'];
        }
        //奖扣对象
//        $user_name = input('user_name','');
        $user_id = $params['user_id']??'';
        if($user_id) $where['u1.id'] = $user_id;
        //工号
//        $job_number = input('job_number','');
        $job_number = $params['job_number']??'';
        if($job_number) $where['u1.job_number'] = $job_number;
        //事件描述
//        $jevent_desc = input('event_desc','');
        $jevent_desc = $params['event_desc']??'';
        if($jevent_desc) $where['e.event_desc'] = ['like','%'.$jevent_desc.'%'];
        //审核状态
//        $status = input('status','');
        $status = $params['status']??'-1';
        if($status != -1){
            $where['b.status'] = $status;
        }
        //奖扣时间
//        if(input('award_deduction_time_start','') && input('award_deduction_time_end','')){
        if($params['award_deduction_time_start']??'' && $params['award_deduction_time_end']??''){

            $award_deduction_time_start = strtotime($params['award_deduction_time_start']);
            $award_deduction_time_end = strtotime($params['award_deduction_time_end'])+ 24*3600-1;
            $where['b.prize_buckle_time'] = ['between', [$award_deduction_time_start,$award_deduction_time_end]];
        }else{
            $params['month'] = $params['month']??1;
        }
        //记录时间
//        if(input('record_time_start','') && input('record_time_end','')){
        if($params['record_time_start']??'' && $params['record_time_end']??'' ){
            $record_time_start = strtotime($params['record_time_start']);
            $record_time_end = strtotime($params['record_time_end']);
            $where['b.create_time'] = ['between', [$record_time_start,$record_time_end]];
        }


        //获取本月,月初时间。
        $baseDay = strtotime(date('Y-m-01',time()));
        $lastDay = strtotime(date('Y-m-'. date('t').' 23:59:59',time()));

        switch ($params['month']??''){
            case 1:        //本月
                $where['b.prize_buckle_time'] = ['between', [$baseDay,$lastDay]];
                break;
            case 2:        //上月
                $preDay = strtotime( date('Y-m',strtotime('-1 month') ));
                $where['b.prize_buckle_time'] = ['between', [$preDay,$baseDay-1]];
                break;
            case 3:        //最近两月
                $preTwoDay = strtotime( date('Y-m',strtotime('-2 month') ));
                $where['b.prize_buckle_time'] = ['between', [$preTwoDay,$baseDay-1]];
                break;
            default:
                break;
        }

        return $where;
    }

    //选择事件 author:zj
    public function event_daily_search()
    {
        //事件
        $eventLists = M('com_event_cate')
            ->where('com_id', 'in', [0,$this->com_id])
            ->field('id,pid,name')
            ->select();
        $eventList = toTree($eventLists);
        return $eventList;
    }

    /**
     * 选择事件ajax author:zj
     * @param $id       事件id
     * @return array
     */
    public function ajax_event_child($id = 1)
    {
        //获取选择事件分类下的所有id
        $return_data = array(
            'code'=>1,
            'msg'=>'失败',
        );
        if(!request()->isAjax()) echo (json_encode($return_data)); exit;

        $return_data = array(
            'code'=>0,
            'msg'=>'成功',
            'data'=>$this->event_child_ids($id)
        );
        echo (json_encode($return_data));
    }

    //查询指定事件分类下所有子集信息 author:zj
    private function event_child_ids($id){
        $tmpIds = [$id];
        $ids = [];
        while (true) {
            $tmpIds = db('com_event_cate')->where(['pid'=>['in', $tmpIds], 'com_id'=>$this->com_id])->column('id');
            $ids = array_merge($ids, $tmpIds);
            if(!$tmpIds) break;
        }
        $event_child_info = db('com_event a')
            ->join('com_event_cate b', 'a.cate_id = b.id')
            ->join('com_event_cate c', 'b.pid = c.id')
            ->where(['a.cate_id'=>['in', $ids], 'a.com_id'=>$this->com_id])
            ->field('a.*,b.name cate_name,c.name p_cate_name')
            ->select();
        return $event_child_info;
    }

    //积分管理->我的审核 author:zj
    public function my_audit(){
        $where = [];
        //搜索条件
        $prize_buckle_time = trim(input('prize_buckle_time', '', 'addslashes'));
        if($prize_buckle_time){
            $prize_buckle_time = month3($prize_buckle_time);
            $where['prize_buckle_time'] = [ ['>=', $prize_buckle_time[0]], ['<=', $prize_buckle_time[1]], 'and' ];
        }else{
            $month3 = month3();
        }
        input('theme', '', 'trim')                && $where['theme'] = ['like', '%'.trim(input('theme', '', 'addslashes')).'%'];//事件主题
        input('first_check_user_id', 0, 'intval') && $where['first_check_user_id'] = input('first_check_user_id', 0, 'intval');//初审人
        input('last_check_user_id', 0, 'intval')  && $where['last_check_user_id'] = input('last_check_user_id', 0, 'intval');//终审人
        input('record_user_id', 0, 'intval')      && $where['record_user_id'] = input('record_user_id', 0, 'intval');//记录人
        input('status', -1, 'intval') != -1       && $where['status'] = input('status', 0, 'intval');//审核状态
//        $where['prize_buckle_time'] = [ ['>=', $month3[0]], ['<=', $month3[1]], 'and' ];
        $create_time = trim(input('create_time', '', 'addslashes'));
        if($create_time){
            $create_time = month3($create_time);
            $where['create_time'] = [ ['>=', $create_time[0]], ['<=', $create_time[1]], 'and' ];
        }

        $list_type = input('list_type', 0, 'intval'); //列表类型 0全部 1待我审核 2我已审核 3抄送给我的奖扣

        if($list_type == 1){
            $list = db('com_integral_prize_buckle')->where($where)->where(function ($query) {
                $query->where("first_check_user_id = {$this->user_id} and status = 0")->whereOr("last_check_user_id = {$this->user_id} and status = 1");
            })->order('create_time desc')->paginate('', false, page_param());
        }elseif($list_type == 2){
            $list = db('com_integral_prize_buckle')->where($where)->where(function ($query) {
                $query->where(['first_check_user_id'=>$this->user_id, 'status'=>1])->whereOr("last_check_user_id = {$this->user_id} and status = 2");
            })->order('create_time desc')->paginate('', false, page_param());
        }elseif($list_type == 3){
            $where['copy_user_id'] = $this->user_id;
            $list = db('com_integral_prize_buckle')->where($where)->order('create_time desc')->paginate('', false, page_param());
        }else{
            $where['first_check_user_id|last_check_user_id'] = $this->user_id;
            $list = db('com_integral_prize_buckle')->where($where)->order('create_time desc')->paginate('', false, page_param());
        }
        //该企业的用户列表
        $users_data = M('users')->where(['com_id'=>$this->com_id])->column('id,name');
        $return = [
            'list'=>$list,
            'users_data'=>$users_data
        ];
        $this->assign($return);
        return $this->fetch();
    }

    //奖扣->我的审核.初审|终审-通过 author:zj
    public function audit_pass()
    {
        $auditId = input('id');
        $check_opinion = input('check_opinion','');     //审核意见
        $record_add_integral = input('record_add_integral',0);     //记录人额外加分
        $first_add_integral = input('first_add_integral',0);      //初审人额外加分

        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if( $err = \app\common\lib\EventCheck::audit_pass($auditId, $record_add_integral, $first_add_integral, $check_opinion) ) return $this->ajaxReturn(1,$err);

        return $this->ajaxReturn(0,'审核通过');
    }

    //奖扣.初审|终审-批量通过 author:zj
    public function audit_pass_list(){
        $ids = explode(',', input('id'));//批量通过id数组
        $err = '';
        $tmpErr = '';
        foreach($ids as $k=>$v){
            if($v && intval($v)){
                $record_add_integral = input('record_add_integral',0);     //记录人额外加分
                $first_add_integral = input('first_add_integral',0);      //初审人额外加分
                $tmpErr = \app\common\lib\EventCheck::audit_pass($v, $record_add_integral, $first_add_integral);
            }

            if(!empty($tmpErr)) {
                $theme = $auditInfo = M('com_integral_prize_buckle')->where('id', $v)->value('theme');
                $err .= $theme . $tmpErr .";";
            }
        }
        if(!empty($err)){
            return $this->ajaxReturn(1,$err);
        }
        return $this->ajaxReturn(0,'审核通过');
    }

    //奖扣.催审 author:zj
    public function audit_urge()
    {
        $auditId = input('id');
        if(!$auditInfo = M('com_integral_prize_buckle')->where('id', $auditId)->find()) return $this->ajaxReturn(1,'非法操作');

        //消息通知
        if($auditInfo['status'] == 1) {
            $user_id = $auditInfo['last_check_user_id'];
        }else{
            $user_id = $auditInfo['first_check_user_id'];
        }
        \app\company\logic\Message::send_message('您有事件被催审，请尽快处理', $user_id, 5, 3, $auditInfo['id']);

        return $this->ajaxReturn(0,'催审成功');
    }

    //奖扣.提交 author:zj
    public function audit_sub()
    {
        $auditIdArr = explode(',', input('id'));
        $check_opinion = input('check_opinion','');
        foreach($auditIdArr as $k=>$v){
            $auditId = $v;
            if(!$auditId) return $this->ajaxReturn(1,'操作失败');
            if(!$inofs = M('com_integral_prize_buckle')->where('id', $auditId)->where('record_user_id',$this->user_id)->find()) return $this->ajaxReturn(1,'非法操作，不是相关记录人');
            $saveData = [
                'id'=>$auditId,
                'status'=>0
            ];

            if($this->user_id == $inofs['first_check_user_id']){
                $saveData['first_check_opinion'] = $check_opinion;
                $saveData['status'] = 1;
            }

            DB::startTrans();//开启事务
            try{
                M('com_integral_prize_buckle')->update($saveData);

                //提醒消息
                //初审通过，发送终审消息
                if($saveData['status'] == 1) { //发送终审消息
                    $user_id = $inofs['last_check_user_id'];
                    $title = '当前有一条任务记录需要您审核(终审)';
                    \app\company\logic\Message::send_message($title, $user_id, 1, 2, $auditId);
                }else{
                     //记录人
                    $data_message[] = [
                        'title' => '您有一条记录已通过初审',
                        'user_id' => $inofs['record_user_id'],
                        'cate_type' => 4,//积分奖扣消息
                        'type' => 3,//积分奖扣
                        'relation_id' => $auditId
                    ];
                    //终审人
                    $data_message[] = [
                        'title' => '您有一条奖扣记录需要您审核(终审)',
                        'user_id' => $inofs['last_check_user_id'],
                        'cate_type' => 1,//审核消息
                        'type' => 3,//积分奖扣
                        'relation_id' => $auditId
                    ];
                    \app\company\logic\Message::send_message_list($data_message);

                }

                DB::commit();//提交
            }catch (\Exception $e){
                DB::rollback();//回滚
                return $this->ajaxReturn(1, $e->getMessage());
            }
        }
        return $this->ajaxReturn(0,'提交成功');
    }

    //奖扣.编辑 author:zj
    public function audit_edit(Request $request){

        if ($request->isPost()) {
            return $this->index_store($request);
        }

        $id = input('event_id',0) > 0 ? input('event_id') : I('id', 0);

        $list = [];

        $c_i_p_bInfo = M('com_integral_prize_buckle')->find($id);
        //初终抄送人
        $buckle_user = db('users u')
            ->join('com_department d', 'd.id=u.department_id')
            ->where([
                'u.id'=>['in', [$c_i_p_bInfo['first_check_user_id'], $c_i_p_bInfo['last_check_user_id'], $c_i_p_bInfo['copy_user_id']]]
            ])
            ->column('u.id, u.name, d.name as d_name');
        $list['theme']['first_check_user_id'] = $c_i_p_bInfo['first_check_user_id'];    //初审人
        $list['theme']['last_check_user_id'] = $c_i_p_bInfo['last_check_user_id'];      //终审人
        $list['theme']['copy_user_id'] = $c_i_p_bInfo['copy_user_id'];                  //抄送人
        $list['theme']['theme'] = $c_i_p_bInfo['theme'];  //主题
        $list['theme']['desc'] = $c_i_p_bInfo['desc'];  //备注
        $list['theme']['prize_buckle_time'] = date('Y-m-d H:i:s', $c_i_p_bInfo['prize_buckle_time']);  //奖扣时间
        $list['theme']['id'] = $c_i_p_bInfo['id'];//id
        //一个主题可有多个事件
        $eventIds = M('com_integral_prize_buckle_relation_event')->where([
            'com_id'=>$this->com_id,
            'prize_buckle_id'=>$c_i_p_bInfo['id'],
        ])->select();

        foreach ($eventIds as $k=>$v) {
            //$v['event_id']  是事件id
            $list['event'][$v['id']]['list'] = M('com_integral_event_relation_users ru')
                ->join('users u', 'u.id=ru.user_id', 'LEFT')
                ->join('com_department d', 'd.id=u.department_id', 'LEFT')
                ->join('com_integral_prize_buckle_relation_event e', 'e.id=ru.event_id', 'LEFT')
                ->where([
                    'ru.com_id'=>$this->com_id,
                    'ru.event_id'=>$v['id'],
                    'e.event_id'=>$v['event_id'],
                ])
                ->field('ru.*, u.name as user_name, u.job_number, d.name as d_name, e.event_id as event_id')
                ->select();
            $event_info = M('com_event a')
                ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
                ->join('com_event_cate c', 'c.id=b.pid', 'left')
                ->field('a.*,b.name cate_name,c.name p_cate_name')
                ->where('a.id',$v['event_id'])->find();

            $list['event'][$v['id']]['cate_name'] = $event_info['cate_name'];                     //分类
            $list['event'][$v['id']]['p_cate_name'] = $event_info['p_cate_name'];                     //上级分类
            $list['event'][$v['id']]['is_piece'] = $event_info['is_piece'];                     //是否是记件事件
            $list['event'][$v['id']]['is_check'] = $event_info['is_check'];                     //是否是专人审核
            $list['event'][$v['id']]['is_lottery_ticket'] = $event_info['is_lottery_ticket'];   //是否是奖票事件
            $list['event'][$v['id']]['is_lock_first'] = $event_info['is_lock_first'];   //专审事件初审人是否锁定
            $list['event'][$v['id']]['is_lock_last'] = $event_info['is_lock_last'];   //专审事件终审人是否锁定
            $list['event'][$v['id']]['name'] = $event_info['name'];
            $list['event'][$v['id']]['integral_a_start'] = $event_info['integral_a_start'];
            $list['event'][$v['id']]['integral_a_end'] = $event_info['integral_a_end'];
            $list['event'][$v['id']]['integral_b_start'] = $event_info['integral_b_start'];
            $list['event'][$v['id']]['integral_b_end'] = $event_info['integral_b_end'];
            $list['event'][$v['id']]['id'] = $event_info['id'];
            foreach($eventIds as $k2=>$v2){
                if($v2['id'] == $v['id']){
                    $list['event'][$v['id']]['event_desc'] = $v2['event_desc'];
                }
            }
        }
//        var_dump($list);die;
        //用户弹窗 准备删除
        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->field('a.id,a.name,b.name department_name')
            ->where('a.com_id',$this->com_id)
            ->select();
        $this->assign('users', $users);
        //事件弹窗 准备删除
        $where_1['a.com_id'] = $this->com_id;
//        $where_1['a.type'] = 1;//正式库
        $where_1['a.type'] = input('event_id',0) > 0 ? 2 : 1;
        $where_1['a.is_check'] = 0;//排除专审事件
        $event = M('com_event a')
            ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
            ->join('com_event_cate c', 'c.id=b.pid', 'left')
            ->field('a.*,b.name cate_name,c.name p_cate_name')
            ->where($where_1)->select();
        $this->assign('event', $event);

    //    dump($list);die;
//        dump($buckle_user);
//        dump($eventIds);
//        die;

        $this->assign('list',$list);
//        var_dump($list);die;
        $this->assign('buckle_user',$buckle_user);

        $this->base_department_page();
        $this->base_event_cate();

        return $this->fetch();
    }

    //奖扣.删除 author:zj
    public function audit_del()
    {
        $idArr = explode(',', I('id', 0));
        foreach($idArr as $k=>$v){
            $id = $v;
            if(!$id) return $this->ajaxReturn(1,'非法操作');
            //获取该主题下的：积分奖扣事件关联表id
            $c_i_p_bInfo = M('com_integral_prize_buckle')->find($id);
            //获取该主题下的所有prize_buckle_id关联的id
            $eventIds = M('com_integral_prize_buckle_relation_event')->where([
                'com_id'=>$this->com_id,
                'prize_buckle_id'=>$c_i_p_bInfo['id'],
            ])->column('id');
            DB::startTrans();//开启事务
            try{
                //com_integral_prize_buckle
                //com_integral_prize_buckle_relation_event
                //com_integral_event_relation_users
                M('com_integral_prize_buckle')->where('id',$c_i_p_bInfo['id'])->delete();
                M('com_integral_prize_buckle_relation_event')->where([
                    'com_id'=>$this->com_id,
                    'prize_buckle_id'=>$c_i_p_bInfo['id'],
                ])->delete();
                M('com_integral_event_relation_users')->where('id','in',$eventIds)->delete();
                DB::commit();//提交
            }catch (\Exception $e){
                DB::rollback();//回滚
                return $this->ajaxReturn(1, $e->getMessage());
            }
        }

        return $this->ajaxReturn(0,'删除成功');
    }

    //奖扣.撤回 author:zj
    public function audit_withdraw($auditId=0){
        $auditId = $auditId ? $auditId : input('id');
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if(!$res = M('com_integral_prize_buckle')->where('id', $auditId)->find()) return $this->ajaxReturn(1,'非法操作');

        $arr = [
            0=>4,
            1=>0,
            2=>1
        ];

        $saveData = [
            'id'=>$auditId,
            'status'=>$arr[$res['status']]
        ];

        if($res['record_user_id'] == $this->user_id) $saveData['check_status'] = 1;

        DB::startTrans();//开启事务
        try{
            M('com_integral_prize_buckle')->update($saveData);
            //撤回终身通过的一切操作
            if( $res['status'] == 2 ){
                \app\common\lib\EventCheck::audit_withdraw($res);
            }
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1, $e->getMessage());
        }

        return $this->ajaxReturn(0,'撤回成功');
    }

    //奖扣.批量撤回 author:zj
    public function audit_withdraw_list(){
        $auditId = explode(',', input('id'));
        foreach($auditId as $k=>$v){
            if($v && intval($v)){
                $this->audit_withdraw($v);
            }
        }
        return $this->ajaxReturn(0,'撤回成功');
    }

    //奖扣.zj驳回 author:zj
    public function audit_reject($id = 0){
        $auditId = $id ? $id : input('id');
        $check_opinion = input('check_opinion','');                 //驳回意见
        $record_add_integral = input('record_add_integral',0);     //记录人额外加分
        $first_add_integral = input('first_add_integral',0);      //初审人额外加分
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');

        if(!$check_opinion && input('id')) return $this->ajaxReturn(1,'必须填写驳回意见');      //单个驳回才判断

        if(!$auditInfo = M('com_integral_prize_buckle')->where('id', $auditId)->where('last_check_user_id|first_check_user_id',$this->user_id)->find()) return $this->ajaxReturn(1,'非法操作，不是相关审核人');

        if($auditInfo['status'] < 1) {
            $data['reject_type'] = 1;
            $data['check_status'] = 2;
            $data['first_check_opinion'] = $check_opinion;
        }else{                      //1待终审
            $data['reject_type'] = 2;
            $data['check_status'] = 2;
            $data['last_check_opinion'] = $check_opinion;
        }
        $data['status'] = 4;

        //修改状态为4
        DB::startTrans();//开启事务
        try{
            M('com_integral_prize_buckle')->where('id', $auditId)->update($data);
            if($auditInfo['status'] == 1) {
                if($record_add_integral){//扣减记录人
                    \app\common\lib\SendIntegralNew::add_record_integral($auditInfo,-abs($record_add_integral),0,33);
                }
                if($first_add_integral){//初审人分值
                    \app\common\lib\SendIntegralNew::add_record_integral($auditInfo,-abs($record_add_integral),0,34);
                }
            }
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
        return $this->ajaxReturn();
    }
    //奖扣.zj批量驳回 author:zj
    public function audit_reject_list(){
        $auditId = explode(',', input('id'));
        foreach($auditId as $k=>$v){
            if(intval($v)){
                $this->audit_reject($v);
            }
        }
        return $this->ajaxReturn();
    }

    //请假审核-》审核页面，初审、终审、驳回    author:zj
    public function leave_check_store()
    {
        $params = input();
        $data = [];
//        $check_opinion = input('check_opinion','');                 //驳回意见

        if(!in_array($params['check_status'],[1,2])) return $this->ajaxReturn(1,'非法操作');

        if($params['check_status'] == 2 && $params['check_desc'] == '') return $this->ajaxReturn(1,'必须填写驳回意见');

        if($params['check_status'] == 1){       //通过
            if( $err = \app\common\lib\LeaveCheck::leave_pass($params['id'], $params['check_desc'])) return $this->ajaxReturn(1,$err);
        }else{                                  //驳回
            $data['status'] = 3;
            if($params['status'] < 1){  //0待初审核
                $data['reject_type'] = 1;
                $data['check_status'] = 2;
                $data['first_check_desc'] = $params['check_desc'];
            }else{                      //1待终审
                $data['reject_type'] = 2;
                $data['check_status'] = 2;
                $data['last_check_desc'] = $params['check_desc'];
            }

            DB::startTrans();//开启事务
            try{
                db('com_leave')->where('id',$params['id'])->update($data);
                DB::commit();//提交
            }catch (\Exception $e){
                DB::rollback();//回滚
                return $this->ajaxReturn(1,$e->getMessage());
            }
            $auditInfo = M('com_leave')->where('id', $params['id'])->find();
            $user_id = $auditInfo['user_id'];
            $title = '您有一条请假审核被驳回';
            $relation_id = $auditInfo['id'];
            \app\company\logic\Message::send_message($title, $user_id, 3, 4, $relation_id);
        }
        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/leave_check'));
    }

    //请假，列表页提交    author:zj
    public function leave_sub()
    {
        $leaveId = input('id');
        $check_opinion = input('check_opinion','');//审核意见
        if(!$leaveId) return $this->ajaxReturn(1,'操作失败');
        if(!$auditInfo = M('com_leave')->where('id', $leaveId)->where('user_id',$this->user_id)->find()) return $this->ajaxReturn(1,'非法操作，不是审请人');

        $saveData = [
            'id'=>$leaveId,
            'status'=>0
        ];

        if($this->user_id == $auditInfo['first_check_user_id']){
            $saveData['first_check_opinion'] = $check_opinion;
            $saveData['status'] = 1;
            $saveData['first_check_time'] = time();
        }

        DB::startTrans();//开启事务
        try{
            M('com_leave')->update($saveData);

            $relation_id = $auditInfo['id'];
            //审核，后续事件
            if($saveData['status'] == 1) {
                $user_id = $auditInfo['last_check_user_id'];
                $title = '您有请假记录待审核(终审)';
                \app\company\logic\Message::send_message($title, $user_id, 1, 4, $relation_id);
                //通知`last_check_user_id` '终审人',初审通过
            }else{
                $user_id = $auditInfo['first_check_user_id'];
                $title = '您有请假记录待审核(初审)';
                \app\company\logic\Message::send_message($title, $user_id, 1, 4, $relation_id);
            }

            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1, $e->getMessage());
        }
        return $this->ajaxReturn(0,'提交成功');
    }

    public function activity_import_1()
    {
        if($_FILES['file']['error'] != 0){
            return $this->ajaxReturn(1, "文件上传有误");
        }
        //文件是否大于2M
        if($_FILES['file']['size'] > 102400*5){
            return $this->ajaxReturn(1, "文件最大5M");
        }
        $r = action('file/controller_up');
        if($r['err'] != 0){
            return $this->ajaxReturn(1, "文件保存出错");
        }
        $path = ROOT_PATH.'public'.$r['data']['saveName'];
        $type = 'Xlsx';//设置为Xls代表支持2003或以下版本，Xlsx代表2007版
        $xlsReader = IOFactory::createReader($type);
        $xlsReader->setReadDataOnly(true);
        $Sheets = $xlsReader->load($path);
        $dataArray = $Sheets->getSheet(0)->toArray();
        unlink($path);

        $data = [];
        $time = time();
        unset($dataArray[0]);       //删除第一行，从第二行开始读取
        foreach ($dataArray as $key=>$row){

            if(!$row[0]) return $this->ajaxReturn(1,'分类名称不能为空');

            if( !is_numeric($row[2]) || $row[2] < 0 || !is_numeric($row[3]) || $row[3] < 0 || !is_numeric($row[4]) || $row[4] < 0 || !is_numeric($row[5]) || $row[5] < 0) {
                return $this->ajaxReturn(1,'分值必须为正整数');
            }

            if(!in_array($row[6],[0,1])) return $this->ajaxReturn(1,'是否是奖票事件字段值必须是0或1');

            if(!in_array($row[7],[0,1])) return $this->ajaxReturn(1,'是否是记件事件字段值必须是0或1');

            if(!$catId = M('com_event_cate')->where('name', $row[0])->where('com_id', 'in', [0,$this->com_id])->find()) {
                return $this->ajaxReturn(1,'未找到名称为'.$row[0].'分类');
            }

            $data[] = [
                'com_id' => $this->com_id,
                'type' =>1,
                'create_time' => $time,
                //--------------------
                'cate_id' => $catId['id'],
                'name' => $row[1],
                'integral_a_start' => $row[2],
                'integral_a_end' => $row[3],
                'integral_b_start' => $row[4],
                'integral_b_end' => $row[5],
                'is_lottery_ticket' => $row[6],
                'is_piece' => $row[7],
                'desc' => $row[8],
            ];
        }

        DB::startTrans();
        try{
            echo M('com_event')->insertAll($data);
            DB::commit();
            return $this->ajaxReturn(0,'导入成功');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }
    //事件库导入@stone
    public function activity_import(){
        set_time_limit(0);
        if($_FILES['file']['error'] != 0){
            return $this->ajaxReturn(1, "文件上传有误");
        }
        //文件是否大于2M
        if($_FILES['file']['size'] > 102400*5){
            return $this->ajaxReturn(1, "文件最大5M");
        }
        $r = action('file/controller_up');
        if($r['err'] != 0){
            return $this->ajaxReturn(1, "文件保存出错");
        }
        $path = ROOT_PATH.'public'.$r['data']['saveName'];
        $type = 'Xlsx';//设置为Xls代表支持2003或以下版本，Xlsx代表2007版
        $xlsReader = IOFactory::createReader($type);
        $xlsReader->setReadDataOnly(true);
        $Sheets = $xlsReader->load($path);
        $dataArray = $Sheets->getSheet(0)->toArray();
        unlink($path);
        $data = [];
        $time = time();
        unset($dataArray[0]);       //删除第一行，从第二行开始读取
        unset($dataArray[1]);       //删除第二行，从第三行开始读取
        $err_msg = '';
        //查询事件分类
        $where = 'com_id = 0 or com_id = '.$this->com_id;
        $event_cate_names = M('com_event_cate')->where($where)->column('name');
        $event_cate_ids = M('com_event_cate')->where($where)->column('id','name');
        //查询事件
        $event_names = M('com_event')->where('com_id',$this->com_id)->column('name');
        $event_names_id = M('com_event')->where('com_id',$this->com_id)->column('id','name');
        foreach ($dataArray as $key=>$row){
            $index = $key + 1;
            if(!empty($row[0])) {
                //字段验证
//                var_dump($row);die;
                if (empty($row[0])||empty($row[1])||($row[2] === NULL)||($row[3] === null)||($row[4] === null)||($row[5] === null)||($row[6] === null)||($row[7] === null)){
                    $err_msg .= '第'.$index.'行数据缺失';
                }
                //事件分类验证
                if (!in_array($row[0], $event_cate_names)){
                    $err_msg .= '第'.$index.'行事件分类不存在';
                }
                //事件验证
                if (in_array($row[1], $event_names)){
//                    $err_msg .= '第'.$index.'行事件已存在';
                }else{
//                    array_push($event_names,$row[1]);
                }
                //验证A分B分
                if($row[2]>$row[3] || $row[4]>$row[5]){
                    $err_msg .= '第'.$index.'行AB分值范围不正确';
                }
                //验证奖票计件
                if(!in_array($row[6], [0, 1]) || !in_array($row[7], [0, 1])){
                    $err_msg .= '第'.$index.'行奖票计件数组不正确';
                }
                if (in_array($row[1], $event_names)){
                    $data_update[] = [
                        'id'=>$event_names_id[$row[1]],
                        'com_id' => $this->com_id,
                        'type' => 1,
                        'cate_id' => $event_cate_ids[$row[0]] ?? 0,
                        'name' => $row[1],
                        'integral_a_start' => $row[2],
                        'integral_a_end' => $row[3],
                        'integral_b_start' => $row[4],
                        'integral_b_end' => $row[5],
                        'is_lottery_ticket' => $row[6],
                        'is_piece' => $row[7],
                        'desc' => $row[8],
                        'is_del'=>0
                    ];
                }else {
                    $data[] = [
                        'com_id' => $this->com_id,
                        'type' => 1,
                        'create_time' => $time,
                        'cate_id' => $event_cate_ids[$row[0]] ?? 0,
                        'name' => $row[1],
                        'integral_a_start' => $row[2],
                        'integral_a_end' => $row[3],
                        'integral_b_start' => $row[4],
                        'integral_b_end' => $row[5],
                        'is_lottery_ticket' => $row[6],
                        'is_piece' => $row[7],
                        'desc' => $row[8],
                    ];
                }
            }
        }
        if(!empty($err_msg)){
            return $this->ajaxReturn(1,$err_msg);
        }
        DB::startTrans();
        try{
            if(!empty($data)){
                M('com_event')->insertAll($data);
            }
            if(!empty($data_update)){
                dbSaveAll($data_update,'com_event','id');
            }
            DB::commit();
            return $this->ajaxReturn(0,'导入成功');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }


    //事件导入
    public function activity_import_csv()
    {
        $file = request()->file('file');
        $abs_path = ROOT_PATH.'/public';
        $upload_path  =  'uploads'.DS.date("Y").DS.date("m").DS.date("d");
        $fileNameOld = time().'_'.md5(time()+rand(0,10000));
        $info = $file->move($upload_path, $fileNameOld, false);
        $fileUrl = $info==false ? $abs_path.DS.$upload_path.DS.$fileNameOld : $abs_path.DS.$upload_path.DS.$info->getSaveName();
        $csv = Reader::createFromPath($fileUrl, 'r');
        $csv->setHeaderOffset(0);

        $data = [];
        $time = time();
        foreach ($csv as $key=>$v){
            $row = array_values($v);
            $row = implode(',',$row);
            $row= mb_convert_encoding($row, "UTF-8", "GBK"); //已知源码为GBK，转换为utf-8
            $row = explode(',', $row);

            if(!$row[0]) return $this->ajaxReturn(1,'分类名称不能为空');

            if( !is_numeric($row[2]) || $row[2] < 0 || !is_numeric($row[3]) || $row[3] < 0 || !is_numeric($row[4]) || $row[4] < 0 || !is_numeric($row[5]) || $row[5] < 0) {
                return $this->ajaxReturn(1,'分值必须为正整数');
            }

            if(!in_array($row[6],[0,1])) return $this->ajaxReturn(1,'是否是奖票事件字段值必须是0或1');

            if(!in_array($row[7],[0,1])) return $this->ajaxReturn(1,'是否是记件事件字段值必须是0或1');

            if(!$catId = M('com_event_cate')->where('name', $row[0])->where('com_id', 'in', [0,$this->com_id])->find()) {
                return $this->ajaxReturn(1,'未找到名称为'.$row[0].'分类');
            }

            $data[] = [
                'com_id' => $this->com_id,
                'type' =>1,
                'create_time' => $time,
                //--------------------
                'cate_id' => $catId['id'],
                'name' => $row[1],
                'integral_a_start' => $row[2],
                'integral_a_end' => $row[3],
                'integral_b_start' => $row[4],
                'integral_b_end' => $row[5],
                'is_lottery_ticket' => $row[6],
                'is_piece' => $row[7],
                'desc' => $row[8],
            ];
        }

        DB::startTrans();
        try{
            echo M('com_event')->insertAll($data);
            DB::commit();
            return $this->ajaxReturn(0,'导入成功');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }
    //事件视图，导入 author:zj
    public function review_import()
    {
        if ($_FILES['file']['error'] != 0) {
            return $this->ajaxReturn(1, "文件上传有误");
        }
        //文件是否大于100KB
        if ($_FILES['file']['size'] > 102400) {
            return $this->ajaxReturn(1, "文件最大8M");
        }
        $r = action('file/controller_up');
        if ($r['err'] != 0) {
            return $this->ajaxReturn(1, "文件保存出错");
        }
        $path = ROOT_PATH . 'public' . $r['data']['saveName'];
        $type = 'Xlsx';//设置为Xls代表支持2003或以下版本，Xlsx代表2007版
        $xlsReader = IOFactory::createReader($type);
        $xlsReader->setReadDataOnly(true);
        $Sheets = $xlsReader->load($path);
        $dataArray = $Sheets->getSheet(0)->toArray();

        if (count($dataArray) > 200) {
            return $this->ajaxReturn(1, "每次导入最大条数为200条");
        }

        @unlink($path);      //删除文件

        $tmpArr = [];
        unset($dataArray[0]);       //删除第一行，从第二行开始读取
        foreach ($dataArray as $key=>$vv) {
            $msg = '第'.($key+1).'条数据';
            if (!$vv[0]) return $this->ajaxReturn(1, $msg.'主题不能为空');
//            if (!$vv[1]) return $this->ajaxReturn(1, $msg.'备注不能为空');
            if (!$vv[2]) return $this->ajaxReturn(1, $msg.'人员不能为空');
            if (!$vv[3]) return $this->ajaxReturn(1, $msg.'人员工号不能为空');
            if (!strtotime($vv[4])) return $this->ajaxReturn(1, $msg.'时间不能为空或格式不正确');
            if (!$vv[5]) return $this->ajaxReturn(1, $msg.'事件类型不能为空');
            if (!$vv[6]) return $this->ajaxReturn(1, $msg.'事件名称不能为空');
//            if (!$vv[7]) return $this->ajaxReturn(1, $msg.'描述不能为空');
//            if (!$vv[8] && is_numeric($vv[8])) return $this->ajaxReturn(1, $msg.'A分不能为空,并且为数值');
            if (!$vv[9] && is_numeric($vv[9])) return $this->ajaxReturn(1, $msg.'B分不能为空,并且为数值');
            if (!$vv[10]) return $this->ajaxReturn(1, $msg.'初审人不能为空');
            if (!$vv[11]) return $this->ajaxReturn(1, $msg.'初审人工号不能为空');
            if (!$vv[12]) return $this->ajaxReturn(1, $msg.'终审人不能为空');
            if (!$vv[13]) return $this->ajaxReturn(1, $msg.'终审人工号不能为空');

            $md5 = md5($vv[0].$vv[1].$vv[4].$vv[10].$vv[11].$vv[12].$vv[13]);
            $tmpArr[$md5][] = $vv;
        }

        $time = time();
        DB::startTrans();
        try {
            foreach ($tmpArr as $key => $rows) {
            $num = count($rows);        //事件，人次数

            //取该主题下的最大绝对值A分
            $a_score = array_column($rows, '8');
            $aMin = min($a_score);
            $aMax = max($a_score);
            $a_score = abs($aMin) - abs($aMax) >= 0 ? $aMin : $aMax ;

            //取该主题下的最大绝对值B分
            $b_score = array_column($rows, '9');
            $bMin = min($b_score);
            $bMax = max($b_score);
            $b_score = abs($bMin) - abs($bMax) >= 0 ? $bMin : $bMax ;

            //判断初审人存不存在，初审人+工号
            if (!$fuserInfo = M('users')->where([
                'com_id' => $this->com_id,
                'name' => trim($rows[0][10]),
                'job_number' => trim($rows[0][11])
            ])->find()) {
                return $this->ajaxReturn(1, '未找到初审人姓名为' . $rows[0][10] . '，工号为' . $rows[0][11] . '的人');
            }
            //判断初审人是否有，审核权限
            if (!M('com_prize_buckle_relation_users')->where([
                'com_id' => $this->com_id,
                'user_id' => $fuserInfo['id']
            ])->find()) {
                return $this->ajaxReturn(1, '初审人' . $rows[0][10] . '没有审核权限');
            }

            //判断终审人存不存在，终审人+工号
            if (!$luserInfo = M('users')->where([
                'com_id' => $this->com_id,
                'name' => trim($rows[0][12]),
                'job_number' => trim($rows[0][13])
            ])->find()) {
                return $this->ajaxReturn(1, '未找到终审人姓名为' . $rows[0][12] . '，工号为' . $rows[0][13] . '的人');
            }
            //判断终审人是否有，审核权限
            $luser_prize = db('com_prize_buckle_relation_users cu')
                ->join('com_prize_buckle cb', 'cu.prize_buckle_id = cb.id', 'left')
                ->where('cu.com_id', $this->com_id)
                ->where('cb.com_id', $this->com_id)
                ->where('cu.user_id', $luserInfo['id'])
                ->field('cu.user_id, cb.integral_a, cb.integral_b')
                ->find();
            if (!$luser_prize && empty($luser_prize)) return $this->ajaxReturn(1, '终审人' . $rows[0][10] . '没有审核权限');

            //判断,主题+备注+时间+初审人+初审人工号+终审人+终审人工号，如果存在则取id使用，如果不存在，新建主题
            $cipb_Info = M('com_integral_prize_buckle')->where(
                [
                    'com_id' => $this->com_id,
                    'desc' => trim($rows[0][1]),
                    'theme' => trim($rows[0][0]),
                    'first_check_user_id' => $fuserInfo['id'],
                    'last_check_user_id' => $luserInfo['id'],
                    'record_user_id' => $this->user_id,
                    'status'=>0
                ]
            )->find();
            //不存在，新建主题
            if (!$cipb_Info) {
                //新建，得到主题id
                $cipb_data = [
                    'com_id' => $this->com_id,
                    'first_check_user_id' => $fuserInfo['id'],
                    'last_check_user_id' => $luserInfo['id'],
                    'record_user_id' => $this->user_id,
                    'prize_buckle_time' => strtotime($rows[0][4]),
                    'status' => 0,
                    'first_check_time' => $time,
                    'last_check_time' => $time,
                    'theme' => trim($rows[0][0]),
                    'desc' => trim($rows[0][1]),
                    'create_time' => $time,
                ];
                $cipb_Info = $cipb_data;
                $cipb_Id = M('com_integral_prize_buckle')->insertGetId($cipb_data);
            } else {
                $cipb_Id = $cipb_Info['id'];
            }
            foreach ($rows as $row) {

                //判断员工存不存在。人员+工号
                if (!$userInfo = M('users')->where([
                    'com_id' => $this->com_id,
                    'name' => trim($row[2]),
                    'job_number' => trim($row[3])
                ])->find()) {
                    return $this->ajaxReturn(1, '未找到人员姓名为' . $row[2] . '，工号为' . $row[3] . '的人员');
                }

                //查询事件类型
                if (!$eventCateInfo = M('com_event_cate')->where('name', trim($row[5]))->where('com_id', 'in', [0, $this->com_id])->find()) {
                    return $this->ajaxReturn(1, '未找到名称为' . $row[5] . '分类');
                }
                //查询事件，存在则获取Id，不存在则新建事件
                $eventInfo = M('com_event')->where([
                    //                'type'=>1,
                    'name' => trim($row[6]),
                    'cate_id' => $eventCateInfo['id'],
//                    'desc' => trim($row[7]),
                    'com_id'=>$this->com_id
                ])->find();

                if (!$eventInfo) {//未查到事件，去新建
                    $eventSave = [
                        'com_id' => $this->com_id,
                        'cate_id' => $eventCateInfo['id'],
                        'type' => 2,
                        'name' => trim($row[6]),
                        'first_check_user_id' => $fuserInfo['id'],
                        'last_check_user_id' => $luserInfo['id'],
//                        'desc' => trim($row[7]),
                        'create_time' => $time
                    ];
                                    $eventId = M('com_event')->insertGetId($eventSave);
                } else {
                    $eventId = $eventInfo['id'];
                }
                //判断审核权限和分值范围
                if ($eventInfo && $eventInfo['type'] == 1) {   //正式事件
                    if ($row[8] - $eventInfo['integral_a_start'] < 0 || $eventInfo['integral_a_end'] - $row[8] < 0) {   //超标事件
                        if (abs($luser_prize['integral_a']) < $a_score) {  //终审人A分小于填写A分则报错
                            return $this->ajaxReturn(1, '事件' . $row[6] . '所填写A分超出终审人审核权限');
                        }
                    }

                    if ($row[9] - $eventInfo['integral_b_start'] < 0 || $eventInfo['integral_b_end'] - $row[9] < 0) {   //超标事件
                        if (abs($luser_prize['integral_b']) < $b_score) {  //终审人A分小于填写A分则报错
                            return $this->ajaxReturn(1, '事件' . $row[6] . '所填写B分超出终审人审核权限');
                        }
                    }
                }

                //非正式事件或者新增临时事件
                if (!$eventInfo || $eventInfo['type'] != 1) {

                    if (abs($luser_prize['integral_a']) < $a_score) {  //终审人A分小于填写A分则报错
                        return $this->ajaxReturn(1, '事件' . $row[6] . '所填写A分超出终审人审核权限');
                    }

                    if (abs($luser_prize['integral_b']) < $b_score) {  //终审人A分小于填写A分则报错
                        return $this->ajaxReturn(1, '事件' . $row[6] . '所填写B分超出终审人审核权限');
                    }
                }

                //新建事件
                if (!$eventId && isset($eventSave) && !empty($eventSave)) {
                    $eventId = M('com_event')->insertGetId($eventSave);
                }

//                //新建主题、更新主题分值
//                if (!$cipb_Id && isset($cipb_data) && !empty($cipb_data)) {
//                    $cipb_Id = M('com_integral_prize_buckle')->insertGetId($cipb_data);
//                }
//                else{
                    if($row[8] > 0){
                        $cipdUpdate['integral_a_add'] = Db::raw('integral_a_del+'.$row[8]);
                    }else{
                        $cipdUpdate['integral_a_del'] = Db::raw('integral_a_del+'.$row[8]);
                    }
                    if($row[9] > 0){
                        $cipdUpdate['integral_b_add'] = Db::raw('integral_b_add+'.$row[9]);
                    }else{
                        $cipdUpdate['integral_b_del'] = Db::raw('integral_b_del+'.$row[9]);
                    }
                    $cipdUpdate['people_sum'] = Db::raw('people_sum+1');
                    M('com_integral_prize_buckle')->where('id', $cipb_Id)->update($cipdUpdate);
//                }
                //积分奖扣事件关联表
                $c_i_p_b_r_e = [
                    'com_id' => $this->com_id,
                    'prize_buckle_id' => $cipb_Id,
                    'event_id' => $eventId,
                    'event_desc' => trim($row[7]),
                    'create_time' => $time
                ];
                $c_i_p_b_r_e_ID = M('com_integral_prize_buckle_relation_event')->insertGetId($c_i_p_b_r_e);

                //积分奖扣事件参与人关联表
                $c_i_e_r_u = [
                    'com_id' => $this->com_id,
                    'event_id' => $c_i_p_b_r_e_ID,
                    'user_id' => $userInfo['id'],
                    'integral_b' => $row[9],
                    'integral_a' => $row[8]
                ];
                M('com_integral_event_relation_users')->insert($c_i_e_r_u);

//                //添加用户积分
//                if (!empty($row[8])) {
//                    $usersUpdate['integral_a'] = Db::raw('integral_a+' . $row[8]);
//                }
//                if (!empty($row[9])) {
//                    $usersUpdate['integral_b'] = Db::raw('integral_b+' . $row[9]);
//                }
//                M('users')->where('id', $userInfo['id'])->update($usersUpdate);

//                //添加用户积分记录
//                $c_i_l = [
//                    'com_id' => $this->com_id,
//                    'user_id' => $userInfo['id'],
//                    'type' => 0,
//                    'integral_b' => $row[9],
//                    'integral_a' => $row[8],
//                    'create_time' => $time,
//                    'year' => date('Y', $time),
//                    'month' => date('m', $time),
//                    'year_month' => strtotime(date('Y-m', $time)),
//                    'event_id' => $c_i_p_b_r_e_ID,
//                ];
//                M('com_integral_log')->insert($c_i_l);


            }

            //达标固定系统事件
//            $this->sys_fixed_thing($cipb_Info, $num);
        }
            DB::commit();
            return $this->ajaxReturn(0, '导入成功');
        } catch (\Exception $e) {
            DB::rollback();
            return $this->ajaxReturn(1, $e->getMessage());
        }
    }

}
